ChrisBurns
ChrisBurns

Reputation: 319

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

Upvotes: 8

Views: 13141

Answers (2)

jmrobin92
jmrobin92

Reputation: 31

Personally I never trust in toLocaleString function, I prefer to use getMonth and lpad to formatting a date manually.

Another advantage is that you don't depend on anything to do it

function lpad (strModify, intMaxPad) 
{
    if (typeof strModify == 'undefined') 
    {
        return false;
    }
    strModify = strModify.toString();
    return strModify.length < intMaxPad ? lpad("0" + strModify, intMaxPad) : strModify;
}

$(function(){

    var objDate = new Date(2012, 3, 20, 3, 0, 0);
    console.log( lpad((objDate.getMonth() + 1), 2) + '/' + lpad(objDate.getDate(), 2) + '/' + objDate.getFullYear()  );
});

You can also use the Moment Luxon library

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22320

this is because you forget to add hour12:false

const myDate = new Date(2012, 3, 20, 3, 0, 0)
  ,   dateOpt = { month: '2-digit', hour: '2-digit', hour12:false }
  
  
console.log( myDate.toLocaleString(dateOpt) ); // 20/04/2012 à 03:00:00
// or 
console.log( myDate.toLocaleString('en-US',dateOpt) ); // 04, 03

Upvotes: 6

Related Questions