[英]Javascript leading zero
我正在尝试使用getHours和getMinutes在以后的函数中使用它们。 问题是我总是希望最终数字为3或4位数字和2位数字。 当分钟是0-9时,发生的情况是1:04的结果是14。这是我的代码,它不能解决问题。
$hours = (new Date).getHours(),
$mins = (new Date).getMinutes();
function addZero($hours) {
if ($hours < 10) {
$hours = "0" + $hours;
}
return $hours;
}
function addZero($mins) {
if ($mins < 10) {
$mins = "0" + $mins;
}
return $mins;
}
$nowTimeS = $hours + "" + $mins;
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
问题是您有两个具有相同名称的函数,但从未调用过该函数:
$date = new Date();
$hours = $date.getHours(),
$mins = $date.getMinutes();
$nowTimeS = addZero($hours) + "" + addZero($mins);
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
function addZero($time) {
if ($time < 10) {
$time = "0" + $time;
}
return $time;
}
您使用相同的名称两次定义了函数,但从未调用过
也许您正在寻找?
function pad(num) { return ("0"+num).slice(-2); } var d = new Date(), hours = d.getHours(), mins = d.getMinutes(), nowTimeS = pad(hours) + ":" + pad(mins); console.log(nowTimeS)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.