我的数据库中的时间戳是2015-03-03 00:25:39
(请注意,type = timestamp
和我最后的正确时间戳是2015-03-02 01:31:00
。差异应该是大约23小时。但现在问题是网上提供的答案会给我30个小时而不是23个小时。我尝试过的一些代码如下:
$target
是目标日期
CODE 1:
$then = strtotime($target);
$diff = $then - time();
echo sprintf("%s days and %s hours left", date('z', $diff), date('G', $diff));
但它给了我1天6小时的时间。所以30 hours
CODE2:
$seconds = strtotime("$target") - time();
echo $seconds; exit();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
echo $hours;
它给了我类似107388
= 30小时的内容。
CODE 3:
//Convert to date
$datestr= $target;//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
它给了我6个小时
我不知道我做错了什么,更像是我不知道怎么做。 这是我的最后一招,因为我无法找到对我有帮助的解决方案。 希望你的快速反应。
答案 0 :(得分:2)
PHP' DateTime()
(和DateInterval()
)对于日期数学更好,并返回正确的结果:
$date = new DateTime('2015-03-03 00:25:39');
$now = new DateTime('2015-03-02 01:31:00');
$diff = $date->diff($now);
echo $diff->h, ' hours ', $diff->i, ' minutes';
答案 1 :(得分:0)
这是一个非常晚的答案,但你的问题很好,将来很可能会被搜索。
这是online demo。
// this doesn't appreciate any timezone declarations, you'll need to add this if necessary
$target="2015-03-03 00:25:39"; // declare your input
$then=new DateTime($target); // feed input to DateTime
$now=new DateTime(); // get DateTime for Now
$diff=(array)$then->diff($now); // calculate difference & cast as array
$labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second");
$readable=""; // declare as empty string
// filter the $diff array to only include the desired elements and loop
foreach(array_intersect_key($diff,$labels) as $k=>$v){
if($v>0){ // only add non-zero values to $readable
$readable.=($readable!=""?", ":"")."$v {$labels[$k]}".($v>1?"s":"");
// use comma-space as glue | show value | show unit | pluralize when necessary
}
}
echo "$readable";
// e.g. 2 years, 20 days, 1 hour, 10 minutes, 40 seconds