2

I'm using a 24 hour countdown timer that runs in JavaScript. Currently, it uses seconds as its base measurement. I have 86400 listed here but I would like to calculate how many seconds are left until midnight each day, EST (-5). Could someone please demonstrate how I might define that value and insert it for the "time" variable? I've seen other variations of this but I'm having trouble getting it to work for this specific script. Thank you in advance.

<script type="application/javascript">
var myCountdown1 = new Countdown({
time: 86400, // 86400 seconds = 1 day
width:200, 
height:55,  
rangeHi:"hour",
style:"flip"    // <- no comma on last item!
});
</script>
sparecycle
  • 2,038
  • 5
  • 31
  • 58

1 Answers1

8

You can subtract the UNIX timestamp of now, from the UNIX timestamp of midnight:

var now = new Date();
var night = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1, // the next day, ...
    0, 0, 0 // ...at 00:00:00 hours
);
var msTillMidnight = night.getTime() - now.getTime();
var myCountdown1 = new Countdown({
    time: msTillMidnight / 1000, // divide by 1000 to get from ms to sec, if this function needs seconds here.
    width:200, 
    height:55,  
    rangeHi:"hour",
    style:"flip"    // <- no comma on last item!
});

Here you simply set a timer that takes the UNIX timestamp of midnight, and subtracts it from the UNIX timestamp of now, which will result in the amount of milliseconds until midnight. That is the amount of milliseconds it will then wait before executing the script.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • Joey, you are talented sir. Thank you! – sparecycle Jan 31 '14 at 15:02
  • 2
    What happens when now.getDate() is 31? – Aaron Jul 23 '14 at 18:23
  • 1
    @Aaron That's automatically handled. So for example doing `new Date(2000, 11, 32, 0, 0, 0)` (32 December 2000) will result in `Mon Jan 01 2001 00:00:00`. So, even with month or even year changes, simply entering a date number that's too high for that month will add to the next month the amount of days you exceeded the allowed days. **TL;DR:** it still works. – Joeytje50 Jul 24 '14 at 16:43