javascriptdate

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


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 ?


Solution

  • This functionality doesn't exist natively in javascript, you have to either add it yourself (as you have started to do), or, use a package.