views:

49

answers:

2

Hi all,

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" instead of 6 (for example). Are there any parameters that I don't know about? Obviously I could write a function that does it by checking the length and prepending a "0" if need be, but I thought there might be something more streamlined than that.

Thanks.

+2  A: 

As far as I know, there's not. And I do this all the time for converting dates to the XML dateTime format.

It's also important to note that those methods you list return a number, not a string.

You can, of course, add these yourself by modifying Date.prototype.

Date.prototype.getHoursTwoDigits = function()
{
    var retval = this.getHours();
    if (retval < 10)
    {
        return ("0" + retval.toString());
    }
    else
    {
        return retval.toString();
    }
}

var date = new Date();
date.getHoursTwoDigits();
jdmichal
Indeed. Just wanted to delineate the values with something, and quotes were it. Thanks for the clarification
Mega Matt
+2  A: 

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"
Andy E
You young whipper-snappers and your fancy slicing!
jdmichal
Extremely clever, imo. Thanks for the answer!
Mega Matt