如何使用PHP找到两个日期之间的天数?
将日期转换为unix时间戳,然后从另一个时间戳中减去一个日期。这将得到以秒为单位的差值,然后除以86400(一天中的秒数),得到该范围内的大约天数。
如果你的日期格式为25.1.2010,01/25/2010或2010-01-25,你可以使用strtotime函数:
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
使用ceil将天数四舍五入到下一个全天。如果您希望获得这两个日期之间的完整天数,则使用floor。
如果日期已经是unix时间戳格式,则可以跳过转换,只执行$days_between部分。对于更奇特的日期格式,您可能必须进行一些自定义解析以使其正确。
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
使用这个:)
$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;
现在起作用了
$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));
如果需要的话:
$datediff=abs($datediff);
// Change this to the day in the future
$day = 15;
// Change this to the month in the future
$month = 11;
// Change this to the year in the future
$year = 2012;
// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);
echo "There are $days days until $day/$month/$year";
如果你使用的是PHP 5.3 >,这是目前为止最准确的计算绝对差值的方法:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$abs_diff = $later->diff($earlier)->format("%a"); //3
如果你需要一个相对的(带符号的)天数,可以用这个代替:
$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");
$pos_diff = $earlier->diff($later)->format("%r%a"); //3
$neg_diff = $later->diff($earlier)->format("%r%a"); //-3
更多关于php的DateInterval格式可以在这里找到:https://www.php.net/manual/en/dateinterval.format.php
function howManyDays($startDate,$endDate) {
$date1 = strtotime($startDate." 0:00:00");
$date2 = strtotime($endDate." 23:59:59");
$res = (int)(($date2-$date1)/86400);
return $res;
}
$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600;
echo $diff;
如果你想在开始日期和结束日期之间重复所有的日子,我想出了这个:
$startdatum = $_POST['start']; // starting date
$einddatum = $_POST['eind']; // end date
$now = strtotime($startdatum);
$your_date = strtotime($einddatum);
$datediff = $your_date - $now;
$number = floor($datediff/(60*60*24));
for($i=0;$i <= $number; $i++)
{
echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
}
易于使用date_diff
$from=date_create(date('Y-m-d'));
$to=date_create("2013-03-15");
$diff=date_diff($to,$from);
print_r($diff);
echo $diff->format('%R%a days');
详见:https://blog.devgenius.io/how-to-find-the-number-of-days-between-two-dates-in-php-1404748b1e84
从PHP 5.3及以上版本开始,添加了新的日期/时间函数来获得不同:
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
结果如下:
Difference: 1 years, 0 months, 2 days
DateInterval Object
(
[y] => 1
[m] => 0
[d] => 2
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 367
)
希望能有所帮助!
如果你正在使用MySql
function daysSince($date, $date2){
$q = "SELECT DATEDIFF('$date','$date2') AS days;";
$result = execQ($q);
$row = mysql_fetch_array($result,MYSQL_BOTH);
return ($row[0]);
}
function execQ($q){
$result = mysql_query( $q);
if(!$result){echo ('Database error execQ' . mysql_error());echo $q;}
return $result;
}
出于类似的目的,我在我的作曲项目中使用Carbon。
就像这样简单:
$dt = Carbon::parse('2010-01-01');
echo $dt->diffInDays(Carbon::now());
面向对象的风格:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
程序上的风格:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
这是我的改进版本,显示1年2月25天(s),如果通过第二个参数。
class App_Sandbox_String_Util {
/**
* Usage: App_Sandbox_String_Util::getDateDiff();
* @param int $your_date timestamp
* @param bool $hr human readable. e.g. 1 year(s) 2 day(s)
* @see http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates
* @see http://qSandbox.com
*/
static public function getDateDiff($your_date, $hr = 0) {
$now = time(); // or your date as well
$datediff = $now - $your_date;
$days = floor( $datediff / ( 3600 * 24 ) );
$label = '';
if ($hr) {
if ($days >= 365) { // over a year
$years = floor($days / 365);
$label .= $years . ' Year(s)';
$days -= 365 * $years;
}
if ($days) {
$months = floor( $days / 30 );
$label .= ' ' . $months . ' Month(s)';
$days -= 30 * $months;
}
if ($days) {
$label .= ' ' . $days . ' day(s)';
}
} else {
$label = $days;
}
return $label;
}
}
尝试使用碳
$d1 = \Carbon\Carbon::now()->subDays(92);
$d2 = \Carbon\Carbon::now()->subDays(10);
$days_btw = $d1->diffInDays($d2);
你也可以用
\Carbon\Carbon::parse('')
使用给定的时间戳字符串创建一个Carbon date对象。
TL;DR不使用UNIX时间戳。不要利用时间()。如果你这样做了,要做好98.0825%的可靠性失败的准备。使用DateTime(或Carbon)。
正确答案是Saksham Gupta给出的(其他答案也是正确的):
$date1 = new DateTime('2010-07-06');
$date2 = new DateTime('2010-07-09');
$days = $date2->diff($date1)->format('%a');
或在程序上作为一行代码:
/**
* Number of days between two dates.
*
* @param date $dt1 First date
* @param date $dt2 Second date
* @return int
*/
function daysBetween($dt1, $dt2) {
return date_diff(
date_create($dt2),
date_create($dt1)
)->format('%a');
}
需要注意的是:“%a”似乎表示绝对天数。如果您希望它是一个有符号整数,即当第二个日期在第一个日期之前时为负数,则需要使用'%r'前缀(即format('%r%a'))。
如果您确实必须使用UNIX时间戳,请将时区设置为GMT,以避免下面详细介绍的大多数陷阱。
长一点的回答:为什么除以24*60*60(又名86400)是不安全的
大多数使用UNIX时间戳(和86400将时间戳转换为天数)的答案都做出了两个假设,这两个假设放在一起可能会导致错误的结果和难以跟踪的细微错误,甚至在成功部署后几天、几周或几个月就会出现。这并不是说解决方案不管用——它是有效的。今天。但它可能明天就失效了。
第一个错误是没有考虑到当被问到“从昨天到现在已经过去了多少天?”时,如果从现在到“昨天”所表示的时间间隔不到一天,计算机可能会如实回答为零。
通常在将“日”转换为UNIX时间戳时,所获得的是该特定日子的午夜时间戳。
从10月1日午夜到10月15日,15天过去了。但是在10月1日13:00到10月15日14:55之间,15天减去5分钟已经过去了,大多数使用floor()或进行隐式整数转换的解决方案将比预期少报告一天。
那么,“Y-m-d H:i:s是多少天前的?”会得到错误的答案。
第二个错误是把一天等同于86400秒。这几乎总是正确的——它经常发生,以至于人们忽略了它没有发生的时候。但当夏时制开始实施时,两个连续午夜之间的秒距肯定不会达到每年至少两次。跨DST边界比较两个日期将产生错误的答案。
因此,即使您使用强制所有日期时间戳到固定时间的“hack”,比如午夜(当您只指定日-月-年而不指定小时-分-秒时,这也会被各种语言和框架隐式完成;在数据库(如MySQL)中的DATE类型也是如此,这是广泛使用的公式
FLOOR((unix_timestamp(DATE2) - unix_timestamp(DATE1)) / 86400)
or
floor((time() - strtotime($somedate)) / 86400)
will return, say, 17 when DATE1 and DATE2 are in the same DST segment of the year; but even if the hour:minute:second part is identical, the argument might be 17.042, and worse still, 16.958 when they are in different DST segments and the time zone is DST-aware. The use of floor() or any implicit truncation to integer will then convert what should have been a 17 to a 16. In other circumstances, expressions like "$days > 17" will return true for 17.042, even if this will look as if the elapsed day count is 18.
And things grow even uglier since such code is not portable across platforms, because some of them may apply leap seconds and some might not. On those platforms that do, the difference between two dates will not be 86400 but 86401, or maybe 86399. So code that worked in May and actually passed all tests will break next June when 12.99999 days are considered 12 days instead of 13. Two dates that worked in 2015 will not work in 2017 -- the same dates, and neither year is a leap year. And between 2018-03-01 and 2017-03-01, on those platforms that care, 366 days will have passed instead of 365, making 2018 a leap year (which it is not).
因此,如果您真的想使用UNIX时间戳:
use round() function wisely, not floor(). as an alternative, do not calculate differences between D1-M1-YYY1 and D2-M2-YYY2. Those dates will be really considered as D1-M1-YYY1 00:00:00 and D2-M2-YYY2 00:00:00. Rather, convert between D1-M1-YYY1 22:30:00 and D2-M2-YYY2 04:30:00. You will always get a remainder of about twenty hours. This may become twenty-one hours or nineteen, and maybe eighteen hours, fifty-nine minutes thirty-six seconds. No matter. It is a large margin which will stay there and stay positive for the foreseeable future. Now you can truncate it with floor() in safety.
然而,正确的解决方案是,避免神奇常数,四舍五入的拼凑和维护债务,是
use a time library (Datetime, Carbon, whatever); don't roll your own write comprehensive test cases using really evil date choices - across DST boundaries, across leap years, across leap seconds, and so on, as well as commonplace dates. Ideally (calls to datetime are fast!) generate four whole years' (and one day) worth of dates by assembling them from strings, sequentially, and ensure that the difference between the first day and the day being tested increases steadily by one. This will ensure that if anything changes in the low-level routines and leap seconds fixes try to wreak havoc, at least you will know. run those tests regularly together with the rest of the test suite. They're a matter of milliseconds, and may save you literally hours of head scratching.
无论你的解决方案是什么,都要进行测试!
下面的函数funcdiff实现了现实场景中的一个解决方案(碰巧是被接受的解决方案)。
<?php
$tz = 'Europe/Rome';
$yearFrom = 1980;
$yearTo = 2020;
$verbose = false;
function funcdiff($date2, $date1) {
$now = strtotime($date2);
$your_date = strtotime($date1);
$datediff = $now - $your_date;
return floor($datediff / (60 * 60 * 24));
}
########################################
date_default_timezone_set($tz);
$failures = 0;
$tests = 0;
$dom = array ( 0, 31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31 );
(array_sum($dom) === 365) || die("Thirty days hath September...");
$last = array();
for ($year = $yearFrom; $year < $yearTo; $year++) {
$dom[2] = 28;
// Apply leap year rules.
if ($year % 4 === 0) { $dom[2] = 29; }
if ($year % 100 === 0) { $dom[2] = 28; }
if ($year % 400 === 0) { $dom[2] = 29; }
for ($month = 1; $month <= 12; $month ++) {
for ($day = 1; $day <= $dom[$month]; $day++) {
$date = sprintf("%04d-%02d-%02d", $year, $month, $day);
if (count($last) === 7) {
$tests ++;
$diff = funcdiff($date, $test = array_shift($last));
if ((double)$diff !== (double)7) {
$failures ++;
if ($verbose) {
print "There seem to be {$diff} days between {$date} and {$test}\n";
}
}
}
$last[] = $date;
}
}
}
print "This function failed {$failures} of its {$tests} tests";
print " between {$yearFrom} and {$yearTo}.\n";
结果是,
This function failed 280 of its 14603 tests
恐怖故事:“节省时间”的代价
这一切都始于2014年底。一个聪明的程序员决定通过在几个地方插入臭名昭著的“(MidnightOfDateB-MidnightOfDateA)/86400”代码来节省几微秒,这个计算最多需要30秒。这是一个非常明显的优化,以至于他甚至没有记录它,优化通过了集成测试,不知怎么地潜伏在代码中几个月,都没有被发现。
This happened in a program that calculates the wages for several top-selling salesmen, the least of which has a frightful lot more clout than a whole humble five-people programmer team taken together. On March 28th, 2015, the summer time zone engaged, the bug struck -- and some of those guys got shortchanged one whole day of fat commissions. To make things worse, most of them did not work on Sundays and, being near the end of the month, used that day to catch up with their invoicing. They were definitely not amused.
更糟糕的是,他们失去了(已经非常少的)信心,他们认为这个程序不是为了偷偷地欺骗他们而设计的,并且假装——并且获得了——一个完整的、详细的代码审查,用外行的术语运行和注释测试用例(加上接下来几周的许多红地毯式的接待)。
What can I say: on the plus side, we got rid of a lot of technical debt, and were able to rewrite and refactor several pieces of a spaghetti mess that hearkened back to a COBOL infestation in the swinging '90s. The program undoubtedly runs better now, and there's a lot more debugging information to quickly zero in when anything looks fishy. I estimate that just this last one thing will save perhaps one or two man-days per month for the foreseeable future, so the disaster will have a silver, or even golden, lining.
不利的一面是,整个风波让该公司损失了约20万欧元——加上面子,毫无疑问还加上了一些议价能力(因此,还有更多的钱)。
负责“优化”的人在2014年12月换了工作,远早于灾难发生之前,但仍有传言要起诉他索赔。高层认为这是“最后一个人的错”,这让他们不太满意——这看起来像是我们为澄清此事而设的圈套,最终,在那一年剩下的时间里,我们一直不受欢迎,那年夏天结束时,团队中有一人辞职了。
一百次中有九十九次,“86400黑客”会完美地工作。(例如,在PHP中,strtotime()将忽略夏令时,并报告在10月最后一个星期六的午夜到下一个星期一的午夜之间,正好2 * 24 * 60 * 60秒已经过去了,即使这显然不是真的……负负得正)。
女士们,先生们,这只是一个例子。就像使用安全气囊和安全带一样,你可能永远不会真正需要DateTime或Carbon的复杂性(和易用性)。但有一天,你可能会(或你必须证明你想过这件事的那一天)会像小偷一样在夜里出现(可能是在10月的某个周日凌晨2点)。做好准备。
选择的答案不是最正确的答案,因为它将在UTC之外失败。 根据时区(列表),可能会有时间调整创建“没有”24小时的日子,这将使计算(60*60*24)失败。
这里有一个例子:
date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
^-- the output will be **1**
因此,正确的解决方案是使用DateTime
date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");
echo $date2->diff($date1)->format("%a");
^-- the output will be **2**
这个工作!
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
$early_start_date = date2sql($_POST['early_leave_date']);
$date = new DateTime($early_start_date);
$date->modify('+1 day');
$date_a = new DateTime($early_start_date . ' ' . $_POST['start_hr'] . ':' . $_POST['start_mm']);
$date_b = new DateTime($date->format('Y-m-d') . ' ' . $_POST['end_hr'] . ':' . $_POST['end_mm']);
$interval = date_diff($date_a, $date_b);
$time = $interval->format('%h:%i');
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
// display_error($seconds);
$second3 = $employee_information['shift'] * 60 * 60;
if ($second3 < $seconds)
display_error(_('Leave time can not be greater than shift time.Please try again........'));
set_focus('start_hr');
set_focus('end_hr');
return FALSE;
}
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
上面的代码用的很简单。谢谢。
function get_daydiff($end_date,$today)
{
if($today=='')
{
$today=date('Y-m-d');
}
$str = floor(strtotime($end_date)/(60*60*24)) - floor(strtotime($today)/(60*60*24));
return $str;
}
$d1 = "2018-12-31";
$d2 = "2018-06-06";
echo get_daydiff($d1, $d2);
使用这个简单的函数。声明函数
<?php
function dateDiff($firstDate,$secondDate){
$firstDate = strtotime($firstDate);
$secondDate = strtotime($secondDate);
$datediff = $firstDate - $secondDate;
$output = round($datediff / (60 * 60 * 24));
return $output;
}
?>
像这样调用这个函数
<?php
echo dateDiff("2018-01-01","2018-12-31");
// OR
$firstDate = "2018-01-01";
$secondDate = "2018-01-01";
echo dateDiff($firstDate,$secondDate);
?>
你可以通过简单的方法找到约会对象
<?php
$start = date_create('1988-08-10');
$end = date_create(); // Current time and date
$diff = date_diff( $start, $end );
echo 'The difference is ';
echo $diff->y . ' years, ';
echo $diff->m . ' months, ';
echo $diff->d . ' days, ';
echo $diff->h . ' hours, ';
echo $diff->i . ' minutes, ';
echo $diff->s . ' seconds';
// Output: The difference is 28 years, 5 months, 19 days, 20 hours, 34 minutes, 36 seconds
echo 'The difference in days : ' . $diff->days;
// Output: The difference in days : 10398
PHP中两个日期之间的天数
function dateDiff($date1, $date2) //days find function
{
$diff = strtotime($date2) - strtotime($date1);
return abs(round($diff / 86400));
}
//start day
$date1 = "11-10-2018";
// end day
$date2 = "31-10-2018";
// call the days find fun store to variable
$dateDiff = dateDiff($date1, $date2);
echo "Difference between two dates: ". $dateDiff . " Days ";
计算两个日期的差值:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
输出: + 272天
函数的作用是:返回两个DateTime对象之间的差值。
你可以试试下面的代码:
$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));
最简单的方法来找出两个日期之间的天数差
$date1 = strtotime("2019-05-25");
$date2 = strtotime("2010-06-23");
$date_difference = $date2 - $date1;
$result = round( $date_difference / (60 * 60 * 24) );
echo $result;
$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));
看看所有的答案,我写了一个通用函数,适用于所有的PHP版本。
if(!function_exists('date_between')) :
function date_between($date_start, $date_end)
{
if(!$date_start || !$date_end) return 0;
if( class_exists('DateTime') )
{
$date_start = new DateTime( $date_start );
$date_end = new DateTime( $date_end );
return $date_end->diff($date_start)->format('%a');
}
else
{
return abs( round( ( strtotime($date_start) - strtotime($date_end) ) / 86400 ) );
}
}
endif;
一般来说,我使用“DateTime”来查找两个日期之间的天数。但如果出于某种原因,一些服务器设置没有启用'DateTime',它将使用'strtotime()'简单(但不安全)计算。
我阅读了所有以前的解决方案,没有一个使用PHP 5.3工具:DateTime::Diff和DateInterval::Days
DateInterval::Days精确地包含日期之间的天数。没有必要创造一些特别和奇异的东西。
/**
* We suppose that PHP is configured in UTC
* php.ini configuration:
* [Date]
* ; Defines the default timezone used by the date functions
* ; http://php.net/date.timezone
* date.timezone = UTC
* @link http://php.net/date.timezone
*/
/**
* getDaysBetween2Dates
*
* Return the difference of days between $date1 and $date2 ($date1 - $date2)
* if $absolute parameter is false, the return value is negative if $date2 is after than $date1
*
* @param DateTime $date1
* @param DateTime $date2
* @param Boolean $absolute
* = true
* @return integer
*/
function getDaysBetween2Dates(DateTime $date1, DateTime $date2, $absolute = true)
{
$interval = $date2->diff($date1);
// if we have to take in account the relative position (!$absolute) and the relative position is negative,
// we return negatif value otherwise, we return the absolute value
return (!$absolute and $interval->invert) ? - $interval->days : $interval->days;
}
echo '<h3>2020-03-01 - 2020-02-01: 29 days as it\'s a standard leap year</h3>';
echo getDaysBetween2Dates(new DateTime("2020-03-01"), new DateTime("2020-02-01"), false);
echo '<h3>1900-03-01 - 1900-02-01: 28 days as it\'s a "standard" century</h3>';
echo getDaysBetween2Dates(new DateTime("1900-03-01"), new DateTime("1900-02-01"), false);
echo '<h3>2000-03-01 - 2000-02-01: 29 days as it\'s a century multiple of 400: 2000=400x5</h3>';
echo getDaysBetween2Dates(new DateTime("2000-03-01"), new DateTime("2000-02-01"), false);
echo '<h3>2020-03-01 - 2020-04-01: -28 days as 2020-03-01 is before 2020-04-01</h3>';
echo getDaysBetween2Dates(new DateTime("2020-02-01"), new DateTime("2020-03-01"), false);
我已经尝试了答案中几乎所有的方法。但是DateTime和date_create在所有测试用例中都没有给出正确答案。特别在2月和3月或12月和1月进行测试。
所以,我想出了混合溶液。
public static function getMonthsDaysDiff($fromDate, $toDate, $includingEnding = false){
$d1=new DateTime($fromDate);
$d2=new DateTime($toDate);
if($includingEnding === true){
$d2 = $d2->modify('+1 day');
}
$diff = $d2->diff($d1);
$months = (($diff->format('%y') * 12) + $diff->format('%m'));
$lastSameDate = $d1->modify("+$months month");
$days = date_diff(
date_create($d2->format('Y-m-d')),
date_create($lastSameDate->format('Y-m-d'))
)->format('%a');
$return = ['months' => $months,
'days' => $days];
}
我知道,性能方面这是相当昂贵的。你也可以把它扩展到年限。
这段代码为我工作,并用PHP 8版本测试:
function numberOfDays($startDate, $endDate)
{
//1) converting dates to timestamps
$startSeconds = strtotime($startDate);
$endSeconds = strtotime($endDate);
//2) Calculating the difference in timestamps
$diffSeconds = $startSeconds - $endSeconds;
//3) converting timestamps to days
$days=round($diffSeconds / 86400);
/* note :
1 day = 24 hours
24 * 60 * 60 = 86400 seconds
*/
//4) printing the number of days
printf("Difference between two dates: ". abs($days) . " Days ");
return abs($days);
}
推荐文章
- 致命错误:未找到类“SoapClient”
- 我目前使用的是哪个版本的CodeIgniter ?
- 合并两个PHP对象的最佳方法是什么?
- 如何使HTTP请求在PHP和不等待响应
- 新DateTime()与默认值(DateTime)
- 发送附件与PHP邮件()?
- 如何获得当前的路线在Symfony 2?
- 用PHP删除字符串的前4个字符
- mysql_connect():[2002]没有这样的文件或目录(试图通过unix:///tmp/mysql.sock连接)在
- 一个函数的多个返回值
- 如何保存时区解析日期/时间字符串与strptime()?
- 在PHP中使用foreach循环时查找数组的最后一个元素
- 检查数组是否为空
- PHP DOMDocument loadHTML没有正确编码UTF-8
- PHP在个位数数前加上前导零