Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 27, 2023 14:27
Show Gist options
  • Save code-boxx/a611863f39de6dfe55481c0b0170afbb to your computer and use it in GitHub Desktop.
Save code-boxx/a611863f39de6dfe55481c0b0170afbb to your computer and use it in GitHub Desktop.
PHP Compare Dates

COMPARE DATES IN PHP

https://code-boxx.com/compare-dates-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) DATE TIME OBJECT
$dtA = new DateTime("2019-08-07");
$dtB = new DateTime("2017-08-09");
// (B) CAN BE COMPARED USING OPERATORS
if ($dtA > $dtB) { echo "A is later"; }
else if ($dtA < $dtB) { echo "B is later"; }
else { echo "AB are the same"; }
<?php
// (A) UNIX TIMESTAMP
$dtA = strtotime("2019-08-07");
$dtB = strtotime("2017-08-09");
// (B) CAN BE COMPARED USING OPERATORS
if ($dtA > $dtB) { echo "A is later"; }
else if ($dtA < $dtB) { echo "B is later"; }
else { echo "AB are the same"; }
<?php
// (A) WORKS IF DATE IS IN YYYY-MM-DD
$dtA = "2019-08-07";
$dtB = "2019-10-11";
if ($dtA > $dtB) { echo "A is later"; }
else if ($dtA < $dtB) { echo "B is later"; }
else { echo "AB are the same"; }
// (B) THIS WILL NOT WORK
$dtA = "22 APR 1990";
$dtB = "22 JAN 1990";
if ($dtA > $dtB) { echo "A is later"; }
else if ($dtA < $dtB) { echo "B is later"; }
else { echo "AB are the same"; }
<?php
// (A) ARRAY OF DATES
$dates = ["2013-04-05", "2020-04-05", "2017-06-05", "2019-08-07"];
// (B) UNIX TIMESTAMP
$unix = [];
foreach ($dates as $d) { $unix[] = strtotime($d); }
// (C) SORT HIGH TO LOW
arsort($unix);
foreach ($unix as $k=>$u) {
echo "$k - " . date("Y-m-d", $u)."<br>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment