How to Use toLocaleTimeString() Without Seconds in JavaScript
The Date.prototype.toLocaleTimeString() method is a powerful tool for formatting a Date object's time into a human-readable, locale-sensitive string. By default, it often includes seconds, but in many UI designs, you only want to display the hours and minutes.
This guide will teach you how to use the options parameter of toLocaleTimeString() to customize its output and omit the seconds, giving you precise control over the time format.
The Core Method: toLocaleTimeString() and its options
The toLocaleTimeString() method is the standard, modern way to format time for display. Its real power comes from its second argument, an options object that lets you specify exactly which components of the time you want to display and how they should be formatted.
The Syntax
date.toLocaleTimeString(locales, options)
where:
locales(optional): A string or array of strings specifying the language and region (e.g.,'en-US','de-DE').options(optional): An object that configures the output format.
Problem: by default, toLocaleTimeString() might include seconds, which you don't want.
let now = new Date();
// The default format might include seconds, depending on the locale.
console.log(now.toLocaleTimeString('en-US')); // # Output: 3:30:15 PM