Looking for a creative way to be sure values that come from the getHours, getMinutes, and getSeconds() method for the javascript Date object return \"06\" inste
Similar to @jdmichal's solution, posting because I'd prefer something a little shorter:
function pad(n) { return ("0" + n).slice(-2); }
pad(6); // -> "06"
pad(12); // -> "12"
Rather than add individual methods to Date.prototype, you could just add this method to Number.prototype:
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
// Now .pad() is callable on any number, including those returned by
var time = date.getHours().pad(2) + ":"
+ date.getMinutes().pad(2) + ":"
+ date.getSeconds().pad(2);