Explain Codes LogoExplain Codes Logo

How do I use .toLocaleTimeString() without displaying seconds?

javascript
prompt-engineering
functions
time-formatting
Anton ShumikhinbyAnton Shumikhin·Feb 13, 2025
TLDR

For quick and precise time display in Javascript, use .toLocaleTimeString() with the right options to exclude seconds.

const date = new Date(); const timeWithoutSeconds = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); console.log(timeWithoutSeconds); // It's "9:41 AM", we are still on time

Know your tools: .toLocaleTimeString() deep dive

Beyond the basics, some key aspects of .toLocaleTimeString() can be very helpful. Let's look at them in detail:

Cross-browser compatibility: peace of mind

Our method works perfectly across modern browsers, explicitly supported by Firefox, Chrome, Opera, and IE9+. A crucial point to test your script across these platforms for complete assurance.

Advanced formatting options: an ace up your sleeve

The { hour: '2-digit', minute: '2-digit' } parameters effectively suppress seconds, but Javascript gives room for more customization. Using {timeStyle: 'short'} gives a more concise, user-friendly time format display.

Locale-wise personalization: catch the local vibe

The .toLocaleTimeString() method allows for locale-specific time formatting. By specifying a locale like en-GB, you end up presenting British users with a comfortable 24-hour clock format.

const today = new Date(); console.log(today.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit'})); // returns "17:30", bruv!

Hold onto the locale and time zone: home sweet home

A cool thing about .toLocaleTimeString() is that it automatically adjusts to the local time zone of the user. But, flexibility is key in programming. If you crave UTC or any other time zone, the good news is that our method permits timeZone overrides:

const date = new Date(); console.log(date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' , timeZone: 'UTC'})); // UTC never sleeps!

Discover the hidden Depths

The .toLocaleTimeString() function isn't just about whacking off seconds. It boasts a variety of options for customizing the time display. Play around with parameters like {hourCycle: 'h23'} for hour formats, or {weekday: 'long'} to include weekday. Unleash the power, no third-party libraries required!

Remember, your creativity is the limit.