Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove seconds from toLocaleTimeString

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)?/);
like image 804
mate64 Avatar asked Jun 06 '14 16:06

mate64


2 Answers

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"

like image 172
anubhava Avatar answered Sep 19 '22 22:09

anubhava


Just to add another possible combination to achieve this:

(new Date()).toLocaleTimeString().match(/\d{2}:\d{2}|[AMP]+/g).join(' ')
like image 40
Dalorzo Avatar answered Sep 18 '22 22:09

Dalorzo