How to fix date to retrieve minutes/hours with zeros ?
e.g. it's 05:09 AM >
trace(_date.getHours()+":"+_date.getMinutes()); //5:9
but i want 05:09 instead of 5:9 - so how t开发者_开发知识库o add zeros ??
var _date = new Date();
...
_min = _date.getMinutes();
//fix date:
var _str:String = _min.toFixed(1);
_min = Number(_str);
trace(_date.getHours()+":"+_date.getMinutes());
= 5:9 .... -_-
what's wrong ?
You can format it with something like:
minutes_txt:String = _date.getMinutes() < 10 ? "0" + _date.getMinutes() : _date.getMinutes();
which will pad a zero if the minutes is less than 10, and then just trace that instead of only _date.getMinutes
Personally, I would write a more generic routine. I've done it two ways:
More traditional approach:
// Pass in 'value' you want to pad, and 'len' as total length of string
// to be returned to you. For example, value=24, len=6 would return 000024.
public static function padIntWithLeadingZeros2(value:int, len:uint):String
{
var paddedValue:String = value.toString();
if (paddedValue.length < len)
{
for (var i:int = 0, numOfZeros:int = (len - paddedValue.length); i < numOfZeros; i++)
{
paddedValue = "0" + paddedValue;
}
}
return paddedValue;
}
My own style of doing it:
// Pass in 'value' you want to pad, and 'len' as total length of string
// to be returned to you. For example, value=24, len=6 would return 000024.
public static function padIntWithLeadingZeros(value:int, len:uint):String
{
var paddedValue:String = value.toString();
if (paddedValue.length < len)
{
var leadingZeros:String = "0000000000";
paddedValue = leadingZeros.substring(0, (len - paddedValue.length)) + paddedValue;
}
return paddedValue;
}
Turns out that one is as efficient as the other in terms of lapsed time to execute the function. So, it's just a matter of preference.
R. Grimes
精彩评论