16

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)?/);
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
mate64
  • 9,876
  • 17
  • 64
  • 96

2 Answers2

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"

anubhava
  • 761,203
  • 64
  • 569
  • 643
3

Just to add another possible combination to achieve this:

(new Date()).toLocaleTimeString().match(/\d{2}:\d{2}|[AMP]+/g).join(' ')
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • Thank you, but this removes the time completely, when the system format output is set to `hh:mm AM/PM`. – mate64 Jun 06 '14 at 16:46
  • It actually works with your format `hh:mm:ss` AM or PM is optional in the expression – Dalorzo Jun 06 '14 at 16:47