简体   繁体   English

Javascript 中不带前导零的打印时间

[英]Printing Time without leading zero in Javascript

I'm pretty sure this is simple but I am trying to print out the current time in 12-hour format without including the leading zero in the time string.我很确定这很简单,但我试图以 12 小时格式打印出当前时间,而不包括时间字符串中的前导零。 So, for example.所以,例如。

09:30 AM should print as 9:30 AM. 09:30 AM 应打印为 9:30 AM。

The current code I have so far (which prints the version with the leading zero) is this:我到目前为止的当前代码(打印带有前导零的版本)是这样的:

var d = new Date();
var timeString = d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

How can I change the above code to remove the leading zeros when they appear?如何更改上面的代码以在它们出现时删除前导零?

Your code is specifying:您的代码指定:

hour: '2-digit'

Just get rid of that and all is well.只要摆脱它,一切都很好。 :-) :-)

For the US locale, here's what I get:对于美国语言环境,这是我得到的:

const d = new Date();
console.log(
  d.toLocaleTimeString() // 8:40:28 PM
);

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString#using_options另请参阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString#using_options

Use the numeric format for the hour instead of 2-digit使用numeric格式的小时而不是2-digit

var timeString = d.toLocaleTimeString([], {hour: 'numeric', minute:'2-digit'});

 const d = new Date(); console.log(d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})); console.log(d.toLocaleTimeString([], {hour: 'numeric', minute:'2-digit'}));

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

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