Javascript change getHours to 2 digit [duplicate]

2020-05-29 13:21发布

If the hour is less than 10 hours the hours are usually placed in single digit form.

var currentHours = currentTime.getHours ( );

Is the following the only best way to get the hours to display as 09 instead of 9?

if (currentHours < 10)  currentHours = '0'+currentHours;

标签: javascript
3条回答
姐就是有狂的资本
2楼-- · 2020-05-29 13:36

You can't do much better. Maybe you'll like:

var currentHours = ('0'+currentTime.getHours()).substr(-2);
查看更多
\"骚年 ilove
3楼-- · 2020-05-29 13:41

Your's method is good. Also take a note of it

var date = new Date();
currentHours = date.getHours();
currentHours = ("0" + currentHours).slice(-2);
查看更多
狗以群分
4楼-- · 2020-05-29 13:46

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);
查看更多
登录 后发表回答