Search code examples
javascriptjqueryleading-zerogettime

Javascript leading zero


I'm trying to use getHours and getMinutes to use them on a later function. The problem is that I always want the final number to be 3 or 4 digit and 2 digit. What happens is when the minutes are 0-9 the result of 1:04 is 14. This is my code and it doesn't fix the problem.

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

Solution

  • Problem is that you have two functions with same name, but you never call that function:

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