简体   繁体   English

通过>和<运算符比较日期

[英]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). 在我的PHP代码中,我用UTC存储日期和时间,但我也使用mysql来存储日期时间(也在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. 为此目的故意制作Mysql日期格式。

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. PHP:使用strtotime()将日期更改为UNIX时间戳,然后您可以进行比较。


MySQL: MySQL的:

change dataType of date column to DateTime and then u can compare below way: 将date列的dataType更改为DateTime然后你可以比较以下方式:

$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. 时间戳比较会更快,但我不认为在PHP应用程序中可以寻找性能上的微观改进,而且你必须考虑到2030的bug。

I prefer to compare the 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'. 我更喜欢比较'自Unix时代以来的秒数(1970年1月1日00:00:00 GMT)'。 Of course, this is only good for dates on/after 1970. 当然,这只适用于1970年/之后的日期。

Given that $date1 and $date2 are two date variables to compare: 鉴于$ date1和$ date2是要比较的两个日期变量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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