gpt4 book ai didi

php - 在 PHP/MySQL/JavaScript 系统中计算时差

转载 作者:可可西里 更新时间:2023-10-31 23:44:26 26 4
gpt4 key购买 nike

我想知道计算从现在到某一点的时间差的最佳方法是什么,比方说倒计时时间。

我有一个拍卖在某个时间点有关闭时间,这个时间以“DATETIME 00-00-000 00:00:00”的格式存储在 MySQL 记录中。该记录称为关闭时间。

现在在我的网站上,我有通过 PHP 文件获取时间的 JavaScript 代码。 JavaScript 使用 setInterval 1000 每秒循环一次。 PHP 文件从数据库中获取关闭时间,并以这种格式发回

strtotime($result['closetime']);

我得到了请求的时间,我想使用服务器时间,而不是 JavaScript 中的时间,因为用户的时钟可以关闭。

strtotime(date("H:i:s", $_SERVER['REQUEST_TIME']))

我发回这两个时间戳,并在 JavaScript 中计算它们之间的时间差。我使用这个函数来完成它,从 PHP 发回的值我称为 currentTime 和 closeTime,我认为这应该很清楚。

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;
}

我认为这是非常多的代码来完成如此简单的事情。有没有人有更好的解决方案或更“漂亮”的代码。

尽情享受吧!

最佳答案

有一个jquery Countdown Plugin通过 AJAX 支持服务器同步:

来自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;
}

服务器时间.php:

<?php 
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>

关于php - 在 PHP/MySQL/JavaScript 系统中计算时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2020517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com