0

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
Said Darfur
  • 1
  • 1
  • 1

4 Answers4

3

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 '';
}
Matt
  • 72,564
  • 26
  • 147
  • 178
1
document.getElementById('cdown').innerHTML = (daysLeft.toString().length == 1 ? "0" + daysLeft : daysLeft)

This should do the trick.

Matschie
  • 1,227
  • 10
  • 9
0

You can use slice() function here is the example how to use :

('0' + 11).slice(-2) // output -> '11'
('0' + 4).slice(-2)  // output -> '04'
RAVI VAGHELA
  • 811
  • 1
  • 10
  • 12
0
if(daysLeft <= 9) {
    daysLeft = '0' + daysLeft;
}
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623