为什么日期格式函数返回错误答案?

时间:2018-09-09 18:09:36

标签: javascript

我需要格式化日期。我使用功能 Intl.DateTimeFormat ,但我不明白为什么它不能正确格式化 fTime

示例:

const date = new Date()
console.log('Date:', date)

const dateOptions = { year: 'numeric', month: 'numeric', day: 'numeric' }
const timeOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false }

const fDate = new Intl.DateTimeFormat(dateOptions).format(date)
const fTime = new Intl.DateTimeFormat(timeOptions).format(date)
console.log('fDate:', fDate)
console.log('fTime:', fTime)

我期望得到这样的答案(在我的情况下,例如20:10:25) enter image description here

1 个答案:

答案 0 :(得分:1)

您正在将选项传递给locales参数。即使locales可选,也仅表示您不需要为其提供值;这并不意味着您可以尝试跳过它。如果您不想为locales提供值,而是为options提供值,请改为通过undefined

const date = new Date()
console.log('Date:', date)

const dateOptions = { year: 'numeric', month: 'numeric', day: 'numeric' }
const timeOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false }

const fDate = new Intl.DateTimeFormat(undefined, dateOptions).format(date)
const fTime = new Intl.DateTimeFormat(undefined, timeOptions).format(date)
console.log('fDate:', fDate)
console.log('fTime:', fTime)