3

Why does the following not print two digits for the minutes and seconds?

Documentation for Intl.DateTimeFormat.

Note that adding hour12: false to the options for the hour, minute or second formatters has no visible effect.

const DTF = Intl.DateTimeFormat
const ye = (d) => new DTF('en-GB', { year: 'numeric' }).format(d)
const mo = (d) => new DTF('en-GB', { month: '2-digit' }).format(d)
const da = (d) => new DTF('en-GB', { day: '2-digit' }).format(d)
const ho = (d) => new DTF('en-GB', { hour: '2-digit' }).format(d)
const mi = (d) => new DTF('en-GB', { minute: '2-digit' }).format(d)
const se = (d) => new DTF('en-GB', { second: '2-digit' }).format(d)

const format = (d) =>  `${ye(d)}/${mo(d)}/${da(d)} ${ho(d)}:${mi(d)}:${se(d)}`

console.log(format(new Date('2019-01-01T00:00:00Z'))) // 2019/01/01 00:0:0
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    See https://stackoverflow.com/questions/33401520/intl-datetimeformat-options-hash-getting-leading-zeros-with-2-digit – jcpaiva Mar 05 '20 at 11:52
  • 1
    That does not change the formatting for the minutes and seconds in my case. – Ben Aston Mar 05 '20 at 12:07
  • 2
    According to this unresolved Firefox bug, it's a problem with ICU, the underlying lib: https://bugzilla.mozilla.org/show_bug.cgi?id=1284868#c14 – Delapouite Mar 05 '20 at 12:15

1 Answers1

4

Just use formatToParts since that's a known issue.

const DTF = new Intl.DateTimeFormat('in', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })

const dp = DTF.formatToParts(new Date('2019-01-01T01:02:03Z'))
console.log(dp)

console.log(`${dp[4].value}/${dp[2].value}/${dp[0].value} ${dp[6].value}:${dp[8].value}:${dp[10].value}`)
jcpaiva
  • 422
  • 1
  • 6
  • 14