简体   繁体   English

如果小时数小于 10,JavaScript 会在小时前显示一个零

[英]JavaScript display hour with a zero before it if it is less than 10

When using:使用时:

Date.toLocaleTimeString()

is there any way to have it display 01:42:35 PM instead of 1:42:35 PM ?有什么办法让它显示01:42:35 PM而不是1:42:35 PM吗?

I have tried adding in this:我试过添加这个:

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

but it still only produces a single digit hour (unless it is after 10).但它仍然只产生一位数的小时(除非它是在 10 之后)。

If my reading is right, according to the relevant spec , it appears this is intentional. 如果我的阅读是正确的,根据相关规范 ,这似乎是故意的。

  • Else if f is "2-digit", then 如果f是“2位数”,那么
    • Let fv be FormatNumber(nf2, v). 设fv为FormatNumber(nf2,v)。
    • If the length property of fv is greater than 2, let fv be the substring of fv containing the last two characters. 如果fv的length属性大于2,则让fv成为包含最后两个字符的fv的子字符串。

I can't understand why it would be specified that way, but there it is. 我无法理解为什么会这样指定,但确实如此。 If you want to do zero-padding, it seems you'll just need to prepend it yourself. 如果你想做零填充,你似乎只需要自己添加它。

It worked in this way for me 它以这种方式为我工作

var datelocal = new Date(2016, 01, 01, 1, 1, 1).toLocaleTimeString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});

i'm also attached a plunker . 我还附上了一名傻瓜

NOTE : you have to provide new Date() instead of passing date parameters to Date method to get the current date. 注意 :您必须提供新的Date(),而不是将日期参数传递给Date方法以获取当前日期。

Instead of relying on Date.prototype.toLocaleTimeString or similar functions to get the right format in such situations, I tend to use Moment.js in my JavaScript project. 我倾向于在我的JavaScript项目中使用Moment.js ,而不是依赖Date.prototype.toLocaleTimeString或类似的函数来获得正确的格式。 Moment.js is a JavaScript library which is specifically designed to parse, validate, manipulate and display dates. Moment.js是一个JavaScript库,专门用于解析,验证,操作和显示日期。 To get a string for the time in the format you described, you could use: 要以您描述的格式获取时间字符串,您可以使用:

var s = moment().format('hh:mm:ss A');
console.log(s);

This uses the current date. 这使用当前日期。 If you want to use another date, you can do so, too: 如果你想使用另一个日期,你也可以这样做:

var s = moment(new Date(2016, 8, 19, 1, 10)).format('hh:mm:ss A');
console.log(s);

It saves you the hassle of doing your own zero-padding and other similar stuff. 它可以省去你自己的零填充和其他类似的东西的麻烦。

The correct answer is to use "numeric" instead of "2-digit"正确答案是使用“数字”而不是“2-digit”

 const options = {hour: 'numeric', minute: '2-digit', second: '2-digit'}; function ut() { let d = new Date(); document.getElementById('time').innerHTML = d.toLocaleTimeString('de-DE', options); } window.setInterval(ut, 1000);
 #time { font-size: 40px; text-align: center; white-space: nowrap; color: black }
 <div id="time"></div>

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

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