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 cannot prevent the output of seconds . By default, it displays the time format, for example hh:mm:ss or hh:mm AM/PM , etc.

second : representation of the second. Possible values: " numeric ", " 2-digit ".

Source: MDN Link

This means that you cannot use something like {second: false} .


I am looking for a simple stupid solution, remove seconds from the formatted string 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 

These regular expressions do not work :

 time.replace(/:\d\d( |$)/,''); time.replace(/(\d{2}:\d{2})(?::\d{2})?(?:am|pm)?/); 
+7
javascript date regex
source share
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'}); 

like "12:40 PM"

+5
source share

Just add another possible combination to achieve this:

 (new Date()).toLocaleTimeString().match(/\d{2}:\d{2}|[AMP]+/g).join(' ') 
+1
source share

All Articles