繁体   English   中英

控制 JavaScript 中的日期格式

[英]Controlling the format of dates in JavaScript

为什么下面的分钟和秒不打印两位数?

Intl.DateTimeFormat 文档

请注意,将hour12: false添加到小时、分钟或秒格式器的选项中没有明显效果。

 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

只需使用formatToParts,因为这是一个已知问题。

 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}`)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM