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?
You could abstract out the repeated part in your true and false expressions: var hour = (GetHour() < 10 ? '0' : '') + GetHour()
Simon Lieschke
2009-04-27 10:03:49
There is no reason to call the function twice.
Josh Stodola
2009-04-27 21:56:52
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
2009-06-16 09:29:33
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
2009-04-27 08:52:43
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
2009-04-27 08:57:27
A:
If you use the Prototype framework there's a toPaddedString
method that does this.
a = 2;
a.toPaddedString(2)
// results in "02"
morbaq
2009-04-27 09:56:57
+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
2009-04-27 21:56:18