0

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;
  • 3
    JavaScript isn’t PHP, so you have to declare your variables and there’s no reason to start every one with `$`. Anyway, you’re never calling the `addZero` function and you’re also defining it twice (even though both definitions do the same thing). – Ry- Feb 01 '17 at 07:25
  • And will this solve my problem? – Jim Kalligas Feb 01 '17 at 07:27
  • Using the function you declared will solve your problem, yes. – Ry- Feb 01 '17 at 07:29

2 Answers2

1

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;
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

You defined your function twice using the same name and never called it

Perhaps you are looking for this?

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)
mplungjan
  • 169,008
  • 28
  • 173
  • 236