Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two ISO8601 dates strings in PHP

Tags:

php

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
elseif( $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?

like image 968
oompahloompah Avatar asked Feb 23 '11 22:02

oompahloompah


People also ask

How can I compare two dates in PHP?

Once you have created your DateTime objects, you can also call the diff() method on one object and pass it the other date in order to calculate the difference between the dates. This will give you back a DateInterval object. $last = new DateTime( "25 Dec 2020" ); $now = new DateTime( "now" );

Can PHP compare date strings?

You can PHP date compare with current date by using the strtotime() function along with comparison operators. The date_diff() function allows you to compare two dates and find the difference between them.


2 Answers

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.

like image 122
chx Avatar answered Sep 28 '22 02:09

chx


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)  .....
like image 41
Pekka Avatar answered Sep 28 '22 00:09

Pekka