Comparing two ISO8601 dates strings in PHP

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

I need to compare (actually rank/sort) dates in a PHP script. The dates are ISO-8601 Date format i.e.

YYYY-MM-DD

I wrote a comparison function which splits the dates and compares by year/month/day. However, it seems this may be overkill and I could just as easily done a simple string comparison like:

if ($date1  $date2)    //do something else else    //do yet another thing 

Is my assumption about (ISO-8601) Date string comparison correct - i.e. can I get rid of my function (to save a few clock cycles on the server), or is it safer to explicity do the comparison in a custom function?

回答1:

http://en.wikipedia.org/wiki/ISO_8601#General_principles

Date and time values are organized from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second. The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years. This allows dates to be naturally sorted by, for example, file systems.

Go ahead with string sorting. If wikipedia is not enough, then surely http://www.ietf.org/rfc/rfc3339.txt is, search for strcmp in there.



回答2:

If you turn your dates into DateTime objects (Usually available from PHP 5.2+), you can reliably use comparisons regardless of format.

$date = new DateTime("YYYY-MM-DD"); $date2 = new DateTime("YYYY-MM-DD");  if ($date > $date2)  ..... 


回答3:

If you have two dates in ISO 8601 format then, yes, you can compare them as strings. And this solution have best performance:

Test name       Repeats         Result          Performance      string          10000           0.031393 sec    +0.00% strcmp          10000           0.040579 sec    -29.26% strtotime       10000           0.149791 sec    -377.15% DateTime        10000           0.184489 sec    -487.68% 

Test source here.



回答4:

If you have at least PHP 5.2, I would recommend Pekka's answer. If that's not an option, you can convert the date to a number and compare it numerically:

if(strtotime('YYYY-MM-DD') > strtotime('YYYY-MM-DD')) {    // code } 

Edit:

As Maerlyn pointed out in the comments, the Unix epoch has a limited range. If you are guaranteed to have zeros in front of the 1-digit months and dates, you could also use strcmp:

if(strcmp('2011-05-04', '2011-04-05') > 0) {    // First date is larger } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!