JDe*_*gns 5 javascript php mysql jquery date
如何使用PHP获得倒计时?
我想展示类似3Days 4Hours的东西.我有一个来自MySQL表的日期字段,想要用今天的日期计算它.截至目前,我只有日期,而不是存储在数据库中的时间,但最终我会.所以在那个时候,我可能会表现为3Days 4小时10分钟43秒.
这是我尝试过但得到错误的答案:
$datetime1 = new DateTime($starton);//$starton - date stored in db
$datetime2 = new DateTime(date());
$interval = $datetime1->diff($datetime2);
echo $interval->format('%d days);
Run Code Online (Sandbox Code Playgroud)
如果这基于服务器时间或用户来自的区域工作,我感到困惑.请指导我.当我有时间字段时,我想我可能需要jQuery来显示秒数,所以分钟也是如此.
恕我直言,当您考虑比较时间时,您会自动开始谈论 Unix 时间。本质上,Unix 时间是以秒为单位的计数,并且始终递增。当您有 2 个 Unix 时间戳时,您可以使用简单的算术来计算差异,然后将差异转换为人类可读的形式。
请注意,Unix 时间戳在几乎所有编程语言中都很常见,因此您可以选择是在 PHP、MySQL 还是 JavaScript 中执行此操作,结果可能都是相同的。我将向您展示 PHP 版本。
所以你想这样做:
PHP代码:
//Unix timestamp to Dec. 21, 2012 (midnight)
$unix_time = mktime(0,0,0,12,21,2012);
//Connect to MySQL
//"INSERT INTO table (target_timestamp) VALUES ($unix_time);"
//----- user goes to page -----
//Connect to MySQL
$sql = "SELECT target_timestamp FROM table WHERE foo = bar";
$unix_time = do_query($sql);//do_query not defined, assume it gets the timestamp
$current_time = time();
$diff = $unix_time - $current_time
//$diff should be positive and not 0
if( 1 > $diff ){
exit('Target Event Already Passed (or is passing this very instant)');
} else {
$w = $diff / 86400 / 7;
$d = $diff / 86400 % 7;
$h = $diff / 3600 % 24;
$m = $diff / 60 % 60;
$s = $diff % 60;
return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}
Run Code Online (Sandbox Code Playgroud)