Javascript 将 getHours 更改为 2 位数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18889548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript change getHours to 2 digit
提问by ngplayground
If the hour is less than 10 hours the hours are usually placed in single digit form.
如果小时数少于 10 小时,则小时数通常以个位数形式放置。
var currentHours = currentTime.getHours ( );
Is the following the only best way to get the hours to display as 09
instead of 9
?
以下是让小时显示为09
而不是的唯一最佳方法9
吗?
if (currentHours < 10) currentHours = '0'+currentHours;
回答by Praveen
Your's method is good. Also take a note of it
你的方法很好。也记下它
var date = new Date();
currentHours = date.getHours();
currentHours = ("0" + currentHours).slice(-2);
回答by Dipesh Parmar
You can do this using below code,
您可以使用以下代码执行此操作,
create function,
创建函数,
function addZeroBefore(n) {
return (n < 10 ? '0' : '') + n;
}
and then use it as below,
然后如下使用它,
c = addZeroBefore(deg);
回答by Paul
You can't do much better. Maybe you'll like:
你不能做得更好。也许你会喜欢:
var currentHours = ('0'+currentTime.getHours()).substr(-2);