试图根据数据库中的一些输入在PHP中创建一个简单的倒计时器,这将稍微调整结束时间(使用常量基数)。然而,似乎在倒计时中不断呕吐真正奇怪的数字。我几乎保证我的数学在某处错了。
PHP
$timeUntil = 10; // for tweaking time remaining (days), this will be dynamic in actual program but will always be an integer
$timeStamp = 1445438099; // timestamp of roughly 2 months in the future
$zUnixDays = $timeUntil * 86400; // converting integer (days) into seconds
$zFinalTime = $timeStamp - $zUnixDays; //tweaking the constant time with the variable time
$remaining = $zFinalTime - time(); // seconds remaining from the future time til now
$seconds_remaining = $remaining%60;
$minutes_remaining = floor(($remaining%3600)/60);
$hours_remaining = floor(($remaining%86400)/3600);
$days_remaining = floor(($remaining%2592000)/86400);
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
JS
var result = JSON.parse(results);
var zDays = result[0];
var zHours = result[1];
var zMinutes = result[2];
var zSeconds = result[3];
这应该在大约50天后返回(2个月 - 10天......非常粗糙),而是返回21天。任何人的想法?
答案 0 :(得分:1)
使用DateTime,它更容易:
$future = new DateTime();
$future->setTimestamp(1445438099); // passing in to constructor directly is wonky
$start = $future->sub(new DateInterval('P10D'));
$diff = $start->diff(new DateTime());
$interval = $diff->format('%y:%m:%d:%h:%i:%s');
// 0:1:20:23:29:45
list($year, $month, $day, $hour, $minute, $second) = explode(':', $interval);
答案 1 :(得分:1)
<?php
$daysToFuture = 10;
// 10 Days in Future
$futureTs = mktime(0,0,0,date("n"),date("j")+$daysToFuture,date("Y"));
// remaining till now ...
$remaining = $futureTs-time();
// in Days
$days_remaining = date("d",$remaining);
echo "<pre>"; print_r($days_remaining); echo "</pre>";
// in hours
$hours_remaining = date("H",$remaining);
echo "<pre>"; print_r($hours_remaining); echo "</pre>";
// in minutes
$minutes_remaining = date("i",$remaining);
echo "<pre>"; print_r($minutes_remaining); echo "</pre>";
// in seconds
$seconds_remaining = date("s",$remaining);
echo "<pre>"; print_r($seconds_remaining); echo "</pre>";
// Array
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo "<pre>"; print_r($zTimeCombined); echo "</pre>";
答案 2 :(得分:1)
我建议您使用DateTime和DateInterval个对象
$dateTime = new DateTime();
$dateTime->setTimestamp(1445438099);
$timeInTheFuture = $dateTime->modify('-10 days');
$dateInterval = $timeInTheFuture->diff(new DateTime());
echo json_encode(explode(' ', $dateInterval->format('%d %h %i %s')));