javascript - 为什么 2 位数字不适用于 Date.toLocaleTimeString?

标签 javascript date

我发誓我这样做是对的,正如描述的那样on MDN :

(new Date()).toLocaleTimeString(undefined, {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
})

但这是输出 "3:13:22 AM"....小时不是两位数。我究竟做错了什么?我很累。

最佳答案

hour:'2-digit' 属性似乎被主要的 Chrome、Firefox、Safari 和 NodeJS 忽略了。相反,他们应用选项 hour12: 值(即 12 或 24 小时制):

hour12:true results in "3:00:00 PM" since no one really writes "03:00:00 PM" with the presence of PM. Doing so may confuse others into thinking that this is 24-hour notation (i.e. 3 AM) if one reads quickly and misses the PM at the end.

hour12:false results in "15:00:00" and "PM" is no longer needed.

因此在您的示例中,如果您想要 24 小时制,只需使用:

let date = (new Date("17 May 2019 3:13:22 AM")).toLocaleTimeString(undefined, {
    hour12: false,
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
})

console.log(date); //03:13:22

关于javascript - 为什么 2 位数字不适用于 Date.toLocaleTimeString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181412/

相关文章:

ios - NSPredicate 按年月日过滤

python - 从对象转换后有没有办法解决不正确的日期?

javascript - 从 json store extjs 获取记录

javascript - 在 Django View 中接收 ajax 发布的对象

javascript - 通过忽略特定列将 HTML 表数据转换为 jQuery 中的 JSON 对象

javascript - D3 Graph - 将图表插入 div

javascript - 如何过滤以相同单词开头的句子数组并使用 JavaScript 创建一个新数组?

javascript - 用时刻严格解析日期

PHP:使用 date() 格式化 php 中的日期数字后缀

java - 使用 Java api 按日期搜索 Lotus Notes