JavaScript 前导零

标签 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;

最佳答案

问题是您有两个同名的函数,但您从未调用该函数:

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

关于JavaScript 前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974131/

相关文章:

jquery - 将 JS 数组传递给 MVC Controller 操作

r - 导入 R 后添加前导零

javascript - Apigee JS SDK 为访客返回 401(未经授权)

php - 在 php 中插入 Javascript 变量

jquery - 如何创建从 CSS 下拉菜单到幻灯片 2 上的 iframe 的链接

javascript - 根据受欢迎程度缩放内容标签

python - 为什么 Python 3 允许 "00"作为 0 的文字,但不允许 "01"作为 1 的文字?

cobol - 抑制 COBOL 中的前导零

javascript - 扩展语法无法破坏数组

javascript - 使用“添加更多表单”按钮创建多个表单