PHP将Datetime对象与当前日期时间进行比较并找到更小的

PHP将Datetime对象与当前日期时间进行比较并找到更小的

问题描述:

I am getting datetime from the user through a form and the datetime entered by him, should be greater than current instance of time to be valid.

I am trying something like this

$input_format = 'd M Y - h:i a';
$date = DateTime::createFromFormat($input_format, $_POST['delivery_time']);
$now = new DateTime();
if(!$date || ($date->diff($now) > 0))
{
   $error .= '* Invalid Delivery Day/Time';
   error_log('WARNING :: Invalid Delivery Time at LINE: '.__LINE__.' in '.__FILE__.'
',3,$logfile);
}

I am having problem in the comparison.I get Object of class DateInterval could not be converted to int as error. What is the correct method to ensure that the entered time is greater than correct instance of time

DateTime::diff returns a DateInterval which has the property invert:

invert

Is 1 if the interval represents a negative time period and 0 otherwise.


So in place of $date->diff($now) > 0 you can use simply $now->diff($date)->invert.

(Note: this isn't strictly "greater than", it's effectively "greater than or equal to". It's easy to flip it around to be so if that's important, but it didn't seem relevant enough to warrant it.)