考虑到午夜是一天的变化,以天为单位获取PHP DateTime的差异 [英] Get a PHP DateTime difference in days, considering midnight as a day change

查看:72
本文介绍了考虑到午夜是一天的变化,以天为单位获取PHP DateTime的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将两个午夜视为日间变化(就像DATEDIFF(DAY) SQL函数一样),最简单的方法来获得两个PHP DateTimes之间的天差是什么?

What is the simplest way to get the difference in days between two PHP DateTimes, considering midnight as a day change (just like the DATEDIFF(DAY) SQL function does)?

例如,从今天的13:00到明天的12:00,即使间隔少于24小时,我也应该得到1(天).

For example, between today at 13:00 and tomorrow at 12:00, I should get 1 (day), even though the interval is less than 24 hours.

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
echo $date1->diff($date2)->days; // 0

推荐答案

您可以忽略日期字符串的时间部分

You could ignore the time portion of the date string

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2013-08-08 12:00:00")));
echo $date1->diff($date2)->days; // 1

这篇关于考虑到午夜是一天的变化,以天为单位获取PHP DateTime的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆