如果两个 DateTime 对象具有相同的日、月和年,我该如何比较? 问题是他们有不同的小时/分钟/秒。
最佳答案
对于 DateTime 对象,没有好的方法可以做到这一点。所以你必须做,比方说,不是那么好的事情。
$nDate1 = clone $date1;
$nDate2 = clone $date2;
//We convert both to UTC to avoid any potential problems.
$utc = new DateTimeZone('UTC');
$nDate1->setTimezone($utc);
$nDate2->setTimezone($utc);
//We get rid of the time, and just keep the date part.
$nDate1->setTime(0, 0, 0);
$nDate2->setTime(0, 0, 0);
if ($nDate1 == $nDate2) {
//It's the same day
}
这会起作用,但就像我说的那样,它并不好。
顺便说一句,最近的经验告诉我最好确保两个日期都在同一时区,所以我添加了代码以防万一。
关于PHP DateTime 相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630346/