Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  99] [ 4]  / answers: 1 / hits: 25157  / 10 Years ago, fri, june 6, 2014, 12:00:00

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(/:dd( |$)/,'');
time.replace(/(d{2}:d{2})(?::d{2})?(?:am|pm)?/);

More From » regex

 Answers
15

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


[#70678] Thursday, June 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trinity

Total Points: 591
Total Questions: 102
Total Answers: 106

Location: Singapore
Member since Sun, Jul 25, 2021
3 Years ago
;