The Date.prototype.toLocaleTimeString()
method returns a string with a language sensitive representation of the time portion of this date. It is available for modern browsers.
Unfortunately, the native function is not able to prevent the output of seconds. By default, it outputs a time format like hh:mm:ss
or hh:mm AM/PM
etc.
second: The representation of the second. Possible values are "
numeric
", "2-digit
".
Source: MDN reference
This means, that you can not use something like {second: false}
.
I'm looking for a simple stupid solution, to remove the seconds from a hh:mm:ss
formatted string.
var date = new Date();
var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
console.log(time); // 15:24:07
This regular expressions don't work:
time.replace(/:\d\d( |$)/,'');
time.replace(/(\d{2}:\d{2})(?::\d{2})?(?:am|pm)?/);
You can use:
var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'})
.replace(/(:\d{2}| [AP]M)$/, "");
btw Google Chrome
returns
new Date().toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
as "12:40 PM"
Just to add another possible combination to achieve this:
(new Date()).toLocaleTimeString().match(/\d{2}:\d{2}|[AMP]+/g).join(' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With