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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:35:09  来源:igfitidea点击:

Javascript change getHours to 2 digit

javascript

提问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 09instead 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);