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?
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" );
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.
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.
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) .....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With