Calculating the time difference in an PHP/MySQL/JavaScript system
I was wondering what the best way is to calculate the difference in time from now to a certain point, let's say the countdown time.
I have an auction that has a closetime at a certain point, this time is stored in a MySQL record in the format " DATETIME 00-00-000 00:00:00 ". This record is called closetime.
Now on my website I have JavaScript code that gets this time via a PHP file. The JavaScript loops every second using setInte开发者_开发技巧rval 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 an awful lot of code do something so simple. Does anyone have a better solution or maybe more 'beautiful' code.
Enjoy!
There is a jquery Countdown Plugin that supports server sync through AJAX:
From the docs:
Synchronise the client's time with that of the server by providing a function that returns the current server date and time. This date and time should take into account the server's timezone and any difference between that time and the client's is applied to the countdown when it is started or changed.
The following example uses a PHP program on the server to return the current server time in a format that can be used directly by the JavaScript callback. You should make sure that your server call is synchronous.
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
serverTime.php:
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
Use Date object.
var d = new Date(difference_in_milliseconds);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours() - 1; //See note
Note: Strangely, hours value is bigger by one than I would expect for reason I don't understand. It looks like "midnight Jan 1, 1970" was at 1 AM :-)
UPDATE: The difference of 1 is due to the offset of my timezone (GMT +1).
Slight change that will solve this:
var d = new Date();
var offset = d.getTimezoneOffset() * 60000;
var d = new Date(difference_in_milliseconds + offset);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours();
This JavaScript library is easy to use and will likely serve you well.
Why not have the php page give you the difference?
$sql = "SELECT UNIX_TIMESTAMP(NOW()) as currentTime, UNIX_TIMESTAMP(closeTime) as closeTime FROM yourTable WHERE yourRecordId = '123'";
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
echo timeRemaining($result['currentTime'], $result['closeTime']);
function timeRemaining($start, $end) {
$dateDiff = $end - $start;
if ($dateDiff <= 0) { return 'Ended'; }
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
return "Ending in $fullDays days, $fullHours hours and $fullMinutes minutes.";
}
Do you really have to get the time through AJAX every 1000 ms? (i suppose that you're hoping for closetime changes? ...)
But if you really must do it this way, i'd suggest getting the time difference directly in MySQL for code simplicity.
$sql = "SELECT TIMEDIFF(NOW(), `CreateTime`) from `Table` WHERE `id`=1;"
精彩评论