簡體   English   中英

JavaScript前導零

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM