php 距离 XYZ 日期还有多少天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/654363/
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
How many days until X-Y-Z date?
提问by JD Isaacks
I am trying to build a count-down widget.
我正在尝试构建一个倒计时小部件。
Given a certain date, whats the easiest way in PHP to determine how many days until that date?
给定某个日期,PHP 中确定距该日期还有多少天的最简单方法是什么?
回答by schnaader
<?php
$cdate = mktime(0, 0, 0, 12, 31, 2009, 0);
$today = time();
$difference = $cdate - $today;
if ($difference < 0) { $difference = 0; }
echo "There are ". floor($difference/60/60/24)." days remaining";
?>
回答by Jeff Hines
Expanding on schnaader's answer, here is a one-liner function that takes a date string as a parameter but only returns the number of days:
扩展施纳德的回答,这是一个单行函数,它以日期字符串作为参数,但只返回天数:
<?php
function days_until($date){
return (isset($date)) ? floor((strtotime($date) - time())/60/60/24) : FALSE;
}
?>
回答by Alejandro Moreno
Days minutes and seconds format:
天分秒格式:
// current time
$today = new DateTime(format_date(time(), 'custom', 'd M Y H:i:s'));
// date to which we want to compare (A Drupal field in my case).
$appt = new DateTime(format_date($yourdate_is_timestamp, 'custom', 'd M Y H:i:s' ));
// Months
$months_until_appt = $appt->diff($today)-> m;
// days
$days_until_appt = $appt->diff($today)-> days;
// hours
$hours_until_appt = $appt->diff($today)-> h;
// minutes
$minutes_until_appt = $appt->diff($today)-> i;
// seconds
$seconds_until_appt = $appt->diff($today)-> s;
echo 'days until: ' . $days_until_appt;
echo 'hours until: ' . $hours_until_appt;
echo 'minutes until: ' . $minutes_until_appt;
echo 'seconds until: ' . $seconds_until_appt;
回答by troelskn
Don't treat dates as integers. Use your database, which has good support for dealing with calendars/time.
不要将日期视为整数。使用您的数据库,它对处理日历/时间有很好的支持。
select datediff("2009-11-12", now())
回答by schuilr
PHP 5.3 has introduced the DateTime class that implements a 'diff' function. See http://www.php.net/manual/en/datetime.diff.php
PHP 5.3 引入了实现“diff”函数的 DateTime 类。见http://www.php.net/manual/en/datetime.diff.php
回答by Bashir Patel
I have just come across this in my code for a live app where the system incorrectly regarded today and tomorrow as today. We have just gone into British Summer Time and this has caused a problem with our app.
我刚刚在我的实时应用程序代码中遇到了这个问题,系统错误地将今天和明天视为今天。我们刚刚进入英国夏令时,这导致我们的应用程序出现问题。
I am now using the following, which is giving me the correct result:
我现在正在使用以下内容,这给了我正确的结果:
function days_away_to($dt) {
$mkt_diff = strtotime($dt) - time();
return floor( $mkt_diff/60/60/24 ) + 1; # 0 = today, -1 = yesterday, 1 = tomorrow
}
Of course, using the DateTime class is the best solution going forward ...
当然,使用 DateTime 类是最好的解决方案......

