php - 从当前页面加载时间到特定时间的剩余时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5906686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php - Time remaining until specific time from current time of page load
提问by Vincent
I have to admit that having not even tried to code this myself this question may be a annoying to some but I'm very surprised that I wasn't able to find a good example on the web of what I'm trying to do. Perhaps I'm just not using the right key words in my searches.
我不得不承认,我什至没有尝试自己编写这个问题,这个问题对某些人来说可能很烦人,但我很惊讶我无法在网上找到我正在尝试做的事情的好例子。也许我只是没有在搜索中使用正确的关键词。
I am trying to calculate the time remaining from now (the time the page loads) until a specific date and time (let's say Wednesday May 11, 2011 12:00PM for example) and display it. I had thought it would be quite easy to find a snippet to accomplish this but no luck so far. Does anyone have some example code they have used to accomplish this before? I don't expect anyone to write this for me from scratch but if I can at least get pointed in the right direction it would be extremely helpful.
我正在尝试计算从现在(页面加载的时间)到特定日期和时间(例如,2011 年 5 月 11 日星期三下午 12:00)的剩余时间并显示它。我原以为找到一个片段来实现这一点很容易,但到目前为止还没有运气。有没有人有一些他们以前用来完成这个的示例代码?我不希望有人从头开始为我写这篇文章,但如果我至少能指出正确的方向,那将非常有帮助。
回答by Jimmy Sawczuk
I'd use the DateIntervaland DateTimefunctions:
我会使用DateInterval和DateTime函数:
$now = new DateTime();
$future_date = new DateTime('2011-05-11 12:00:00');
$interval = $future_date->diff($now);
echo $interval->format("%a days, %h hours, %i minutes, %s seconds");
You'll need a version of PHP that's at least 5.3 to do it this way - otherwise, do what helloandre recommends.
您需要至少 5.3 的 PHP 版本才能这样做 - 否则,请执行helloandre 建议的操作。
回答by Lead Developer
I think it will usefull
我认为它会很有用
$startdate="2008-06-22 20:38:25";
$enddate="2008-06-29 21:38:49";
$diff=strtotime($enddate)-strtotime($startdate);
echo "diff in seconds: $diff<br/>\n<br/>\n";
// immediately convert to days
$temp=$diff/86400; // 60 sec/min*60 min/hr*24 hr/day=86400 sec/day
// days
$days=floor($temp); echo "days: $days<br/>\n"; $temp=24*($temp-$days);
// hours
$hours=floor($temp); echo "hours: $hours<br/>\n"; $temp=60*($temp-$hours);
// minutes
$minutes=floor($temp); echo "minutes: $minutes<br/>\n"; $temp=60*($temp-$minutes);
// seconds
$seconds=floor($temp); echo "seconds: $seconds<br/>\n<br/>\n";
echo "Result: {$days}d {$hours}h {$minutes}m {$seconds}s<br/>\n";
echo "Expected: 7d 0h 0m 0s<br/>\n";
echo "time isss".time();
echo $date = date('Y-m-d H:i:s')";
?>
回答by helloandre
first you'll need to calculate the difference in seconds using time()
and strtotime()
. Then you can translate those seconds into days/hours/minutes/seconds.
首先,您需要使用time()
和计算秒差strtotime()
。然后您可以将这些秒转换为天/小时/分钟/秒。