skip to Main Content

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

2

Answers


  1. In some languages there is a problem when the first character of the hour or minute is 0, but no problem in javascript.

    look https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

    minute : The representation of the minute. Possible values are "numeric", "2-digit".

    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search