If less than double digits add 0, javascript
Hopefully this makes sense,
I have a javascript countdown on my page, when it drops down to single digits, such as '9 days' I need to append a 0 to the beginning.
I'm not sure if this is possible with Javascript so thought I'd ask here, My current code im using is
开发者_运维知识库<!-- countdown -->
today = new Date();
expo = new Date("November 03, 2011");
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (expo.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
document.getElementById('cdown').innerHTML = daysLeft
Change:
document.getElementById('cdown').innerHTML = daysLeft
To:
document.getElementById('cdown').innerHTML = ((daysLeft < 10) ? '0' : '') + daysLeft
This is called the ternary operator, and is shorthand for:
if (daysLeft < 10) {
return '0';
} else {
return '';
}
document.getElementById('cdown').innerHTML = (daysLeft.toString().length == 1 ? "0" + daysLeft : daysLeft)
This should do the trick.
if(daysLeft <= 9) {
daysLeft = '0' + daysLeft;
}
You can use slice() function here is the example how to use :
('0' + 11).slice(-2) // output -> '11'
('0' + 4).slice(-2) // output -> '04'
精彩评论