tags:

views:

219

answers:

5

hi guys, In my javascript iam using GetHour and GetMinutes function.For eg:Current Time is 2:03.If in this case i use GetHour(),it returns 2.Instead i need 02.Can anybody help?

+2  A: 
var hour = GetHour() < 10 ? '0' + GetHour() : GetHour();
Greg
You could abstract out the repeated part in your true and false expressions: var hour = (GetHour() < 10 ? '0' : '') + GetHour()
Simon Lieschke
There is no reason to call the function twice.
Josh Stodola
Well the code I was commenting on already called it three times! Unless the GetHour() calls prove to be a performance issue there is nothing wrong with calling a method multiple times in order to express code more concisely.
Simon Lieschke
A: 

There is no function for that. Use the following to add a leading 0:

var date = new Date();
var hours = new String(date.getHours());

if (hours.length == 1)
{
  hours = "0" + hours;
}
Zaagmans
This will never add a trailing zero. "length" is not a valid property on the value returned from `getHours()`, so the code in the if statement will never run.
JPot
+1 you are correct, I needed to make it a string first, before asking the 'length'.
Zaagmans
A: 

There's a javascript library here which looks like it will handle all sorts of date conversions nicely, including formatting dates so that the month is always two digits.

fearoffours
A: 

If you use the Prototype framework there's a toPaddedString method that does this.

a = 2;
a.toPaddedString(2)
// results in "02"
morbaq
+1  A: 

The obvious answer is to use an IF statement...

var dat = new Date();
var hr = dat.getHour();

if(hr < 10) {
  hr = "0" + hr;
}
Josh Stodola