javascriptdatetimetimedatetime-formatintl

Intl.DateTimeFormat does not bother about '2-digit' or 'numeric'


I want to use IntlDateTimeFormat to provide leading zeros. My code is:

const timeFormatter = Intl.DateTimeFormat(undefined,{minute: '2-digit'});

const date = new Date();
date.setMinutes(4);

console.log(timeFormatter.format(date));  // PRINTS: 4 and not 04

However, when I add second: '2-digit' to the options object. Then it works fine, but also prints seconds (Yes, I can remove it using replace).

What's the difference between '2-digit' and 'numeric' then?

I am ignoring padStart, as of now.

I tried to change the configuration back to 'numeric' instead of '2-digit'. There seems no difference


Solution

  • What's the difference between '2-digit' and 'numeric'?

    Not all options apply to all serializations for all option combinations.

    For (only) the formats which are implemented to support serializing 2-digit minutes in a given language, that setting controls whether or not the minutes will be represented as 1 or 2 digits.

    Formatted strings produced by Intl.DateTimeFormat.prototype.format() are both implementation- and language-dependent, so they are not appropriate for producing strings which need to match exact schemas.

    Other combinations might also produce strings you don't expect:

    const date = new Date(2023, 4, 10, 16, 4, 8);
    
    const printFormatted = (opts) => console.log(new Intl.DateTimeFormat(undefined, opts).format(date));
    
    printFormatted({ minute: "2-digit" });
    printFormatted({ minute: "numeric", second: "numeric" });
    printFormatted({ minute: "numeric", weekday: "long" });
    printFormatted({ minute: "2-digit", weekday: "long" });

    Based on the example code in your question: if your goal is to convert a 1-digit or 2-digit integer to a 2-digit string with a leading 0, then String.prototype.padStart() is the idiomatic solution:

    const date = new Date(2023, 4, 10, 16, 4, 8);
    
    const zeroFour = String(date.getMinutes()).padStart(2, "0");
    
    console.log(zeroFour); // 04