How To Show Hours and Minutes Only With toLocaleTimeString()
When you want to display the time in hours and minutes format using JavaScript, you can use the date.toLocaleTimeString()
method.
This method converts a Date object to a string, using locale settings to display time.
But by default, you'll also see the seconds (which, in many use cases, is not what you want.)
Here's how to show only hours and minutes, omitting seconds and other information.
How to
Use toLocaleTimeString()
with options to specify that you only want to see hours and minutes:
const date = new Date(); const timeString = date.toLocaleTimeString(navigator.language, { hour: "2-digit", minute: "2-digit", }); console.log(timeString); // Output might be "03:45"
What's happening here?
navigator.language
: This is optional but takes the user's locale string from their browser, which means it will end up in their local time too. You can set this asundefined
if you want the default timezone.{ hour: '2-digit', minute: '2-digit' }
: This options object tells the method to include only the hour and minute in the output, both displayed with two digits.
You can pass other options here. One I often find useful is hour12: false
to set the time to a 24-hour clock.