PHP检查两个日期时间是否不在同一日历日 [英] PHP check if two Datetimes are not on the same calendar day
问题描述
我有两个这样的日期时间(日期实际上是$ vars)
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
我遇到了一个(可能很漂亮)简单的问题:如何确定两个日期是否在同一天
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
我不能像 2015/01/01 22那样执行
也是正确的。我也不能这样做:<
:00< 2015/01/01 23:00
I cannot do <
as 2015/01/01 22:00 < 2015/01/01 23:00
would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
,因为它给了我 0
。
THIS 给了我一个有关如何做的想法,但是对于javascript,相当于php的是什么?
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
// UPDATE
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
由于评论,我认为这现在可能是正确的方法,但是现在我得到错误:在字符串上调用成员函数diff()
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//为澄清我想做的更新
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
我只希望天数有所不同,因此对于上面的内容,它应为'1'
(尽管实际上仅相差2小时),例如'2015/01/01 23:00'和'2015/01/03 17:00'
将是'2'
。
I just want to have the difference in days, so for the above it would be '1'
(although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00'
would be '2'
.
推荐答案
只需创建时间设置为00:00:00的日期:
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
或在现有日期将时间重置为零:
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
然后它应该可以工作:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
奖金
如果只想使用日期,请记住在 createFromFormat
中将时间设置为00:00:00或使用进行重置。 setTime
。如果您不会在 createFromFormat
中提供时间,PHP会将其设置为当前时间:
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat
or reset it with setTime
. If you won't provide time in createFromFormat
PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
要解决此问题,您必须:
To fix it, you must either:
-
以格式提供00:00:00时间:
provide 00:00:00 time in format:
$ date = DateTime :: createFromFormat('Ymd H:i:s','2016-01-21 00:00:00');
在日期格式前加上感叹号并省略时间,这将自动将时间设置为00:00:00:
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$ date = DateTime :: createFromFormat('!Ym-d','2016-01-21');
重置创建后的时间:
$ date = DateTime :: createFromFormat('Ym-d','2016-01-21' );
$ date-> setTime(0,0);
这篇关于PHP检查两个日期时间是否不在同一日历日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!