我试着写一个脚本,可以计算两个日期之间的差异,以天为单位,但diff
的行为并不像我需要的那样。
更具体地说,假设我们有以下两个日期/时间:
2015-03-18 23:00
2015-03-19 02:00
实际时差是四个小时,因此diff
运行良好!
但我想知道的是,如果日历日期发生了变化,实际的区别是什么。
因此,在上面的例子中,日历日期有1天的差异。
在以下示例中,
2015-03-18 23:00
2015-03-21 02:00
我差三天。那么我该如何计算这个日期差呢?
目前我使用以下代码:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
$interval = $datetime1->diff($datetime2);
echo "<pre>";
print_r($interval);
echo "</pre>";
结果如下:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 3
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
有什么想法吗?谢谢
一个非常简单的解决方案
注意:只有当天在同一个月时,这才有效。
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$difference = $datetime2->format('d') - $datetime1->format('d'); //3
清洁溶液
您可以删除日期中的所有内容,但删除年份、月份和日期,并使用diff()。
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$datetime1modified = new DateTime($datetime1->format('Y-m-d'));
$datetime2modified = new DateTime($datetime2->format('Y-m-d'));
$difference = $datetime1modified->diff($datetime2modified)->d; //3
您当然可以使用这样的函数:
$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");
$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and
// so on to get the h:m:s out of it
或者,如果你更喜欢php内置函数,那么这样的东西可能适合你的需求:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
致以最良好的问候。
您可以做的是从每个日期中删除时间,然后进行计算。
示例:
$datetime1 ='2009-10-11 23:30';
$datetime2 = '2009-10-12 02:30';
$date1_explode = explode($datetime1,' ');
$date1_explode = explode($datetime1,' ');
$date = $date1_explode[1];
$date = $date2_explode[1];
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime1);
$interval = $date1->diff($date2);
echo "<pre>";
print_r($interval);
echo "</pre>";
如果您不关心时间,只想知道日期是否更改,可以在将日期设置为同一小时后尝试diff
日期:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
// Work on duplicates to not change the original objects if they are needed later
$date1 = clone $datetime1;
$date2 = clone $datetime2;
// Set the same hour on both $date1 and $date2
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);
// Now you can simply compare $date1 to $date2 to see if they are equal
if ($date1 == $date2) {
echo('$datetime1 and $datetime2 are on the same date.');
} else {
echo('$datetime1 and $datetime2 are on different dates.');
}
// Or you can compute the difference
$diff = $date2->diff($date1);
// and format it as you like
echo('There are '.$diff->format('%d').' days between '.$date1.' and '.$date2);