PHP check if two Datetimes are not on the same calendar day

后端 未结 3 842
庸人自扰
庸人自扰 2021-01-22 04:24

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 = \\Date         


        
3条回答
  •  悲&欢浪女
    2021-01-22 05:21

    I think this is one of the few situations where the use of strings for date calculations is justified:

    function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
        return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
    }
    

    This code should be easy to extend to include time zone.

    There're other alternatives but I don't think they're normally worth the effort:

    1. Compare element by element (day, month and year):

      • The PHP DateTime class doesn't offer dedicated functions, only format().
    2. Normalize both dates to a common time and compare with == (not ===):

      • Unless you're using immutable objects you need to clone input or expect side effects

      • You also need to ensure that time exists in the active time zone though midnight is probably safe enough.

    Whatever, YMMV ;-)

提交回复
热议问题