Javascript领先零

时间:2017-02-01 07:25:02

标签: javascript jquery leading-zero gettime

我尝试使用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;

2 个答案:

答案 0 :(得分:1)

问题是您有两个具有相同名称的功能,但您从不调用该功能:

$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;
}

答案 1 :(得分:0)

您使用相同的名称定义了您的函数两次,从未调用它

也许你在找这个?

&#13;
&#13;
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)
&#13;
&#13;
&#13;