Javascript Data Type How to - Format a time string with leading zero based hours and minutes








Question

We would like to know how to format a time string with leading zero based hours and minutes.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from  www .ja  va  2s. c o m-->
    function pad(num) {
      return ("0"+num).slice(-2)
    }
    var time = pad(new Date(2013,4,22,5,0,0,0).getHours())+":"+pad(new Date(2013,4,22,7,25,0,0).getMinutes());
    document.writeln(time)
}
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: