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
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".
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:
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: