I don't understand why hours of searching have left me empty handed. The situation is this: my site users can set a date and time for an event to begin. That date and time are stored in the db as a timestamp. I want to display a countdown for them. So, I query the db
SELECT TIMESTAMPDIFF(SECOND, NOW(), start)
FROM events
WHERE eid = '110';
That returns the number of second remaining until the event is set to begin. All I want is to be able to output, in a span
, the number of days, hours, minutes, & seconds.
Here's the javascript I have thus far:
After reading the comments, searching more, and hacking a few things together, this is my updated code:
<span id="countdown-1"><?php echo $timeToEvent; ?></span>
(If there's a more appropriate way to to get my "seconds 'til event" value to the script, please correct me.)
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
function countdown(id, timer){
function pad(num) {
return num > 9 ? num : '0'+num;
};
timer--;
days = Math.floor( timer / 86400 ),
hours = Math.floor( timer / 3600 ),
mins = Math.floor( timer / 60 ),
secs = Math.floor( timer ),
dd = days,
hh = hours - days * 24,
mm = mins - hours * 60,
ss = secs - mins * 60;
clock = dd + ' days ' + pad(hh) + ':' + pad(mm) + ':' + pad(ss) ;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
window.location.reload(true);
}
}
This code works. However, as I wrote above, I don't know if I ought to be passing the php variable $timeToEvent
to the script more directly. It is slightly annoying that the actual number of seconds appears in the span for about 1 second before the javascript changes it to what I want to see. (By the way, I'm not overly concerned about accuracy in this context; I don't mind the time drift.)