Javascript – Format a time string with zero based hours and minutes in javascript

datejavascript

This is what have tried:

partly pseudocode:

var hours = date1.getHours();
var minutes = date2.getMinutes();

if (hours.length == 1)
    hours = "0" + hours;

if (minutes.length == 1)
    minutes = "0" + minutes;

var time = hours + ':' + minutes;

Is there a smarter way like a formatted string function where I can say:

var minutes = date.getMinutes('mm');
var hours = date.getHours('hh');

so it adds the zeros automatically ?

Best Solution

Here is your code fixed since there is no length on an integer

var hours = date1.getHours();
var minutes = date2.getMinutes();

if (hours<10) hours = "0" + hours;
if (minutes<10) minutes = "0" + minutes;

var time = ""+ hours + ":" + minutes;

You do not need a framework and there is no shorter way to do this

This may be what you mean:

Live demo

function pad(num) {
  return ("0"+num).slice(-2)
}
var time = pad(date1.getHours())+":"+pad(date2.getMinutes());