Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .toLocaleString() not honoring '2-digit'

Original Question: How do I get the hour/month to respect a '2-digit' formatting.

const event = new Date(2012, 3, 20, 3, 0, 0);

Edit... Apologies all, I don't use this very often

The real issue is depending on which version of chrome you are on, it respects this formatting differently:

For example:

new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"

enter image description here

like image 595
ChrisBurns Avatar asked Feb 14 '20 17:02

ChrisBurns


1 Answers

The main problem is that you are passing options in the first parameter, which is for the locale string. options belongs in the second parameter.

You also need to include the other fields (year, day, minute) if you want them in the results.

const event = new Date(2012, 3, 20, 3, 0, 0);
console.log(event.toLocaleString('en-US', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit' }
));

You can pass undefined in the first parameter if you want it to use the user's current locale.

const event = new Date(2012, 3, 20, 3, 0, 0);
console.log(event.toLocaleString(undefined, { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit' }
));
like image 97
Matt Johnson-Pint Avatar answered Sep 20 '22 21:09

Matt Johnson-Pint