Sorting dates with PHP

This should have been much faster, so I’m sharing this. PHP (>5.2) creates and compares dates out of the box with the dateTime class.

This is my use case. I had saved some dates as strings in the database, using the jQuery datepicker. I had to convert them back to dateTime-objects to compare two dates. The proper way to do this is to turn them into objects either by using date_create() or new dateTime(). Note that if you use a string that can’t be recognized, the constructer returns false, and your subsequent comparison functions screams at the boolean.

Here’s that comparison function, and the usort-statement that uses it to sort an array of objects by date:

function cmp($a, $b)
{
$datetime1 = date_create($a->meta_value);
$datetime2 = date_create($b->meta_value);
if ($datetime1 && $datetime2) {
$i = date_diff($datetime1, $datetime2);
}
return ($i->invert);  /* boolean: negative when the date diff is negative */
}
usort($comments, "cmp");

Of course in some perfect universe we’d like all this object creation and type casting done automatically with a special operator ensuring MCC in programming (minimal character count), so that we can write something like:

date1 d= 'now';
date2 d= '20 April 2030';
days2go = date1 - date2;

(Actually, this should be possible already. Anyone has implemented this?)

Leave a Reply

Your email address will not be published. Required fields are marked *