I was wondering what the best way is to calculate the difference in time from now to a certain point, lets say the countdown time.
I have an auction that has a closetime at a certain point, this time is stored in an mysql record in the format " DATETIME 00-00-000 00:00:00 ". This record is called closetime.
Now on my website i have a javascript that gets this time via a php file. The javascript loops every second using setInterval 1000. The php file gets the closetime from the db, and sends it back in this format
strtotime($result['closetime']);
And i get the time of the request, i want to use the server time, and not the time in javascript, because the clock of the user can be off.
strtotime(date("H:i:s", $_SERVER['REQUEST_TIME']))
I send back these two timestamps and calculate the time difference between them in javascript. I use this function to do it, the values send back from php i call currentTime and closeTime, i think this should be clear.
function auctionDelayTime(currentTime,closeTime){
totaldelay = closeTime - currentTime;
if(totaldelay <= 0){
return 'ended';
}else{
if( days=parseInt((Math.floor(totaldelay/86400))) )
totaldelay = totaldelay % 86400;
if( hours=parseInt((Math.floor(totaldelay/3600))) )
totaldelay = totaldelay % 3600;
if( minutes=parseInt((Math.floor(totaldelay/60))) )
totaldelay = totaldelay % 60;
if( seconds=parseInt((Math.floor(totaldelay/1))) )
totaldelay = totaldelay % 1;
return hours+':'+formatTimes(minutes)+':'+formatTimes(seconds);
}
}
function formatTimes(value){
return value < 10 ? '0'+value : value;
}
I think this is a awful lot of code do something so simple. Does anyone have a better solution or maybe a more 'beautiful' code.
enjoy!