How to sort an array of dates and times?

October 26, 2018

In PHP it is very easy to sort an array of dates and times. All you need to do is convert it to a (integer) timestamp, and then do a normal sort. Here are more details:

First, convert the dates into a timestamp

A timestamp is time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). The current timestamp (when this page was last cached, anyway) is: 1601385070 (time()).

Because there is no standard PHP array function for sorting date strings we will have to convert it ourselves. But we can make a closure, and pass that to usort(&$array, $compare_func) (which lets us define our own function to do the comparisons for the sorting)

The custom comparison function for usort takes 2 parameters. It returns either -1, 0, or 1 depending on how they compare (1 if $a is less than $b; -1 if $a is greater than $b; 0 if equal). We can use PHP's spaceship operator for this (<=>) .

Let's set up the data:

<?php
    $dates = [
    "10 September 2000",
    "10 September 2020",
    "9 September 2020",
    "9 September 2000",
    "5 April 1999",
    "20 April 1998",
];

And now the comparison function:

<?php
$compare_function = function($a,$b) {
        $a_timestamp = strtotime($a); // convert a (string) date/time to a (int) timestamp
        $b_timestamp = strtotime($b);
        // new feature in php 7
        return $a_timestamp <=> $b_timestamp;
        /* old way to do it:
                if ($a_timestamp > $b_timestamp) {
                    return -1;
                }
                elseif ($a_timestamp < $b_timestamp) {
                    return 1;
                }
                else {
                    return 0;
                }
        */
                };

Now we have everything we need - let's sort that data!

<?php
        usort($dates, $compare_function);
        var_dump($dates);
array:6 [

0 => "20 April 1998"

1 => "5 April 1999"

2 => "9 September 2000"

3 => "10 September 2000"

4 => "9 September 2020"

5 => "10 September 2020"

]