原始问题:
如何让小时/月遵守“2 位”格式。
const event = new Date(2012, 3, 20, 3, 0, 0);
编辑...
抱歉,我不经常使用这个
真正的问题取决于您使用的 chrome 版本,它以不同的方式尊重这种格式:
例如:
new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"
最佳答案
主要问题是您正在传递 options
在第一个参数中,它用于语言环境字符串。 options
属于第二个参数。
如果您希望结果中包含其他字段(年、日、分钟),还需要包括它们。
const event = new Date(2012, 3, 20, 3, 0, 0);
console.log(event.toLocaleString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit' }
));
您可以通过
undefined
如果您希望它使用用户的当前语言环境,请在第一个参数中。const event = new Date(2012, 3, 20, 3, 0, 0);
console.log(event.toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit' }
));
关于Javascript .toLocaleString() 不遵守 '2-digit',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60230961/