How to sort an array of dates and times?

PHP: How to sort an array of dates and times?

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: 1563562203 (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:

  1.     $dates = [
  3.     "10 September 2000",
  4.     "10 September 2020",
  5.     "9 September 2020",
  6.     "9 September 2000",
  7.     "5 April 1999",
  8.     "20 April 1998",
  9. ];

And now the comparison function:

  1. $compare_function = function($a,$b) {
  3.         $a_timestamp = strtotime($a); // convert a (string) date/time to a (int) timestamp
  4.         $b_timestamp = strtotime($b);
  6.         // new feature in php 7
  7.         return $a_timestamp <=> $b_timestamp;
  9.         /* old way to do it:
  11.                 if ($a_timestamp > $b_timestamp) {
  12.                     return -1;
  13.                 }
  14.                 elseif ($a_timestamp < $b_timestamp) {
  15.                     return 1;
  16.                 }
  17.                 else {
  18.                     return 0;
  19.                 }
  21.         */
  23.                 };

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

  1.         usort($dates, $compare_function);
  2.         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"
webdevetc profile pic



Comments and discussion about How to sort an array of dates and times?


Or see other topics in the PHP language

Or see other languages/frameworks:
Or see random questions

How to set infinite execution time in a PHP script

What is the loop variable in a @foreach loop in Blade?

What are the SPL data structures

How to Extract Query String (from a URL) Into an Associative Array in PHP

What is the difference between var, let and const in Javascript?

What are PHP's PSRs?

How to select all rows for a certain month (or day, year or time), using Eloquent

How to group a SQL statement in brackets/parenthesis


How to make multiple routes share the same URL structure or URL parameters