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
  • 1
    See the accepted answer of this question: http://stackoverflow.com/questions/5366849/convert-1-to-0001-in-javascript - you just need to change `var pad = "00";` – Shadow The GPT Wizard Sep 19 '11 at 08:32

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
  • 74,352
  • 26
  • 153
  • 180
1
document.getElementById('cdown').innerHTML = (daysLeft.toString().length == 1 ? "0" + daysLeft : daysLeft)

This should do the trick.

Matschie
  • 1,237
  • 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
  • 877
  • 1
  • 10
  • 12
0
if(daysLeft <= 9) {
    daysLeft = '0' + daysLeft;
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636