The method
Date.prototype.toLocaleTimeString()
provides a language-sensitive representation of the time part of a date in modern browsers.
Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows the time in formats like hh:mm:ss
or hh:mm AM/PM
.
second: Specifies how the second should be displayed. Options include "
numeric
" and "2-digit
".
Source: MDN reference
This means that you cannot simply use something like {second: false}
.
I am seeking a simple yet effective way to exclude the seconds from a time string formatted as hh:mm:ss
.
var date = new Date();
var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
console.log(time); // 15:24:07
The following regular expressions do not achieve the desired outcome:
time.replace(/:\d\d( |$)/,'');
time.replace(/(\d{2}:\d{2})(?::\d{2})?(?:am|pm)?/);