Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 2-digit not working for Date.toLocaleTimeString?

I would swear I'm doing this right, as described on MDN:

(new Date()).toLocaleTimeString(undefined, {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
})

But this is outputting "3:13:22 AM"....the hour is not 2-digit. What am I doing wrong? I'm very tired.

like image 849
temporary_user_name Avatar asked Sep 12 '25 00:09

temporary_user_name


2 Answers

The hour:'2-digit' property seems to be ignored by major Chrome, Firefox, Safari and NodeJS. Instead they apply the option hour12: value (i.e. 12 or 24-hour notation) instead:

hour12:true results in "3:00:00 PM" since no one really writes "03:00:00 PM" with the presence of PM. Doing so may confuse others into thinking that this is 24-hour notation (i.e. 3 AM) if one reads quickly and misses the PM at the end.

hour12:false results in "15:00:00" and "PM" is no longer needed.

So in your example, if you wanted 24-hour notation, just use:

let date = (new Date("17 May 2019 3:13:22 AM")).toLocaleTimeString(undefined, {
    hour12: false,
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
})

console.log(date); //03:13:22
like image 184
chatnoir Avatar answered Sep 14 '25 14:09

chatnoir


If I understand correctly, are you wanting the output in 24 hours?

let date = new Date().toLocaleTimeString(undefined, {
    hour12: false
});

console.log(date);

EDIT: It seems that your original question is an issue that's been covered prior but classified as a bug. https://bugs.chromium.org/p/chromium/issues/detail?id=507037

like image 38
MatthewHinds Avatar answered Sep 14 '25 14:09

MatthewHinds