简体   繁体   中英

Comparing dates via > and < operators

All across my php code i'm storing dates and times in UTC, but i'm also using mysql to store datetimes (also in utc).

is there any way that date comparisons can fail with the greater than and less than operator?

        $curdate=date('Y-m-d H:i:s');
        if($start_datetime>$curdate)

Nope.
There is no way for them to fail.
Mysql date format is intentionally made for this purpose.

There is not a single reason to convert it in whatever else format to compare.

PHP: change date into UNIX timestamp using strtotime() and then u can compare.


MySQL:

change dataType of date column to DateTime and then u can compare below way:

$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');

var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
strtotime($curdate) < strtotime($start_datetime)

strtotime()返回一个int表示自1970年1月1日以来经过的秒数。这意味着如果$ curdate日期为“2011-01-01 12:00:00”且$ start-datetime为“2011-01-01 12:00: 01“然后$ start-datetime大于$ curdate因为strtotime返回$ start-datetime的整数,它正好比$ curdate大一个。

A direct datetime compare won't fail. You can do that.

A timestamp comparison would be faster, but I don't think such a micro-improvement in performance would be something to look for in a php application, plus you'll have to take into account the 2030 bug.

I prefer to compare the 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'. Of course, this is only good for dates on/after 1970.

Given that $date1 and $date2 are two date variables to compare:

if (date("U",$date1) > date("U",$date2)) {
  // $date1 is more recent than $date2
} else {
  // $date1 is older than (or equal to) $date2
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM