如何使用 PHP 查找两个日期之间的天数?
(new DateTime("2010-01-11"))->diff(new DateTime("2019-08-19"))->days;
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
如果您使用 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
$date1
在 $date2
之前时为负数),请改用 $diff = $date2->diff($date1)->format("%r%a");
。
从 PHP 5.3 及更高版本开始,添加了 new date/time functions 以获得不同:
$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
)
希望能帮助到你 !
$fromDate = "2020-08-29"; $toDate = "2021-03-02"; returns 0 years, 6 months, 4 days. But it should be 6 months, 2 days
[days]
总是一个整数?
TL;DR 不使用 UNIX 时间戳。不要使用时间()。如果你这样做了,如果它的 98.0825% 可靠性让你失望,请做好准备。使用日期时间(或碳)。
正确答案是 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()
或进行隐式整数转换的解决方案会报告一天低于预期。
那么,“多少天前是 Ymd H:i:s”?会产生错误的答案。
第二个错误是将一天等同于 86400 秒。这几乎总是正确的——它经常发生,以至于忽略了它没有发生的时候。但是,当夏令时开始发挥作用时,每年至少两次连续两个午夜之间的距离(以秒为单位)肯定不是 86400。比较跨越 DST 边界的两个日期会产生错误的答案。
因此,即使您使用强制所有日期时间戳为固定小时的“hack”,例如午夜(当您仅指定日-月-年而不是小时-分钟-秒时,各种语言和框架也会隐式完成此操作; MySQL 等数据库中的 DATE 类型也是如此),这是广泛使用的公式
FLOOR((unix_timestamp(DATE2) - unix_timestamp(DATE1)) / 86400)
或者
floor((time() - strtotime($somedate)) / 86400)
当 DATE1 和 DATE2 在一年中的同一 DST 段中时,将返回 17;但即使小时:分钟:秒部分相同,参数也可能是 17.042,更糟糕的是,当它们位于不同的 DST 段并且时区是 DST 时,参数可能是 16.958。使用 floor() 或任何隐式截断到整数都会将本来应该是 17 的值转换为 16。在其他情况下,像 "$days > 17" 这样的表达式将返回 true
对于 17.042,即使这看起来好像经过的天数是 18。
而且事情变得更加丑陋,因为这样的代码不能跨平台移植,因为 some of them may apply leap seconds and some might not.在那些做的平台上,两个日期之间的差异不会是 86400,而是 86401,或者可能是 86399。因此,在 5 月工作并实际通过所有测试的代码将在明年 6 月中断,此时 12.99999 天被视为 12天而不是 13 天。在 2015 年有效的两个日期将在 2017 年无效——相同日期,而且这两年都不是闰年。在 2018-03-01 和 2017-03-01 之间,在那些关心的平台上,366 天将过去而不是 365 天,使 2018 年成为闰年(事实并非如此)。
所以如果你真的想使用 UNIX 时间戳:
明智地使用 round() 函数,而不是 floor()。
作为替代方案,不要计算 D1-M1-YYY1 和 D2-M2-YYY2 之间的差异。这些日期将真正被视为 D1-M1-YYY1 00:00:00 和 D2-M2-YYY2 00:00:00。而是在 D1-M1-YYY1 22:30:00 和 D2-M2-YYY2 04:30:00 之间转换。你总是会得到大约二十个小时的剩余时间。这可能变成二十一小时或十九,也可能是十八小时五十九分三十六秒。不管。这是一个很大的利润空间,在可预见的未来将保持不变并保持积极。现在您可以安全地使用 floor() 截断它。
但是,为了避免魔法常数、四舍五入和维护债务,正确的解决方案是
使用时间库(日期时间、碳等);不要自己动手
使用真正邪恶的日期选择编写全面的测试用例 - 跨越 DST 边界、跨越闰年、跨越闰秒等等,以及常见的日期。理想情况下(对 datetime 的调用很快!)通过从字符串中按顺序组装它们来生成整整四年(和一天)的日期,并确保第一天和被测试日之间的差异稳步增加一个。这将确保如果低级例程和闰秒修复中的任何变化试图造成严重破坏,至少你会知道。
与测试套件的其余部分一起定期运行这些测试。它们只是几毫秒的问题,并且可以为您节省数小时的挠头时间。
不管你的解决方案是什么,测试一下!
下面的函数 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 秒的计算节省几微秒。这是一个如此明显的优化,他甚至没有记录它,优化通过了集成测试,不知何故在代码中潜伏了几个月,都没有被注意到。
这发生在一个计算几个最畅销推销员工资的程序中,其中最少的一个比一个不起眼的五人程序员团队加起来的影响力要大得多。 2015 年 3 月 28 日,夏季时区启动,bug 来袭——其中一些人一整天都得到了丰厚的佣金。更糟糕的是,他们中的大多数人在周日不工作,并且临近月底,利用这一天来补发票。他们肯定没有被逗乐。
更糟糕的是,他们失去了(已经很少)相信程序不会被设计为偷偷控制它们,并假装 - 并获得 - 完整,详细的代码审查,测试用例运行并以外行的方式进行评论(加上很多在接下来的几周内进行红地毯治疗)。
我能说什么:从好的方面来说,我们摆脱了很多技术债务,并且能够重写和重构几块意大利面条混乱,这些混乱可以追溯到 90 年代摇摆不定的 COBOL 侵扰。毫无疑问,该程序现在运行得更好,并且有更多的调试信息可以在任何看起来可疑的情况下快速归零。我估计,在可预见的将来,仅这最后一件事每月可能会节省一两个人日,因此灾难将有一个银色甚至金色的衬里。
不利的一面是,整个骚乱使公司损失了大约 200,000 欧元的前期费用——加上面子,加上毫无疑问的一些议价能力(因此,还有更多的钱)。
负责“优化”的人在 2014 年 12 月换了工作,远在灾难发生之前,但仍有人提出要起诉他要求赔偿损失。高层并不顺利,认为这是“最后一个人的错”——这看起来像是一个让我们澄清此事的安排,最后,我们留在了狗窝里今年剩下的时间,其中一个团队在那个夏天结束时辞职。
一百次中有九十九次,“86400 hack”都会完美运行。 (例如,在 PHP 中,strtotime()
将忽略 DST,并报告在 10 月的最后一个星期六的午夜和下一个星期一的午夜之间,正好经过了 2 * 24 * 60 * 60 秒,即使这显然是 < em>不正确...两个错误会很高兴地使一个正确)。
女士们,先生们,这是一个实例。与安全气囊和安全带一样,您可能永远真正需要 DateTime
或 Carbon
的复杂性(和易用性)。但是你可能的那一天(或者你必须证明你考虑过这一点的那一天)会在晚上像小偷一样出现(可能在 02:00十月的某个星期天)。做好准备。
days between two days in 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
部分。对于更奇特的日期格式,您可能需要进行一些自定义解析才能使其正确。
$day
下午 1 点的 UNIX 时间戳和 $day+1
下午 1 点的 UNIX 时间戳之间的差异在遵守 DST 的时区中并不总是 86400 秒。它可能是 23 或 25 小时的秒数,而不是 24 小时。
易于使用 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');
查看更多信息:http://blog.innovsystems.com/php/get-number-days-between-two-dates-php
$diff
变量)的明确使用。 if ($diff->days > 30) { [doyourstuff]; }
之类的东西
面向对象风格:
$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');
用过这个:)
$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;
现在它可以工作了
好吧,选择的答案不是最正确的答案,因为它会在 UTC 之外失败。根据时区 (list),可能会进行时间调整,创建“没有”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**
date_create()
函数的 date_diff()
效果更好,因为 date_create()
不适用于格式为 'dmY' 的日期字符串。我不知道为什么。
你可以简单地找到日期
<?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
计算两个日期之间的差:
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
产出:+272 天
date_diff() 函数返回两个 DateTime 对象之间的差异。
$start = '2013-09-08';
$end = '2013-09-15';
$diff = (strtotime($end)- strtotime($start))/24/3600;
echo $diff;
我在我的作曲家项目中使用 Carbon 来实现此目的和类似目的。
就像这样简单:
$dt = Carbon::parse('2010-01-01');
echo $dt->diffInDays(Carbon::now());
你可以试试下面的代码:
$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));
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 ";
如果您有以秒为单位的时间(IE unix 时间戳),那么您可以简单地减去时间并除以 86400(每天的秒数)
$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));
并且,如果需要:
$datediff=abs($datediff);
查找两个日期之间天数差异的最简单方法
$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));
function howManyDays($startDate,$endDate) {
$date1 = strtotime($startDate." 0:00:00");
$date2 = strtotime($endDate." 23:59:59");
$res = (int)(($date2-$date1)/86400);
return $res;
}
如果您想回显开始日期和结束日期之间的所有日子,我想出了这个:
$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>";
}
此代码对我有用,并使用 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);
}
这是我的改进版本,如果传递了第二个参数,则显示 1 Year(s) 2 Month(s) 25 day(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;
}
}
$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);
?>
// 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";
如果您使用的是 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;
}
尝试使用碳
$d1 = \Carbon\Carbon::now()->subDays(92);
$d2 = \Carbon\Carbon::now()->subDays(10);
$days_btw = $d1->diffInDays($d2);
你也可以使用
\Carbon\Carbon::parse('')
使用给定的时间戳字符串创建碳日期对象。
不定期副业成功案例分享
$your_date-$now
。