-2

I have a short bit of code comparing two dates that does not seem to be working and I wanted to see if anyone could explain why.

  date_default_timezone_set("America/New_York");
  $today = date("m-d-y");

  $dueDate = date("05-08-21");

  if ($dueDate > $today) {
    echo "<p> Success!";
  }
  else {
    echo "<p> Failure!";
  }

When I run this code I keep getting "Failure!" even though 05/08/21 is in the future.

  • 4
    Possible duplicate of [How to compare two dates in php](https://stackoverflow.com/questions/8722806/how-to-compare-two-dates-in-php) –  Jul 04 '19 at 23:46
  • `date()` returns a string, you really can't compare those –  Jul 04 '19 at 23:47

2 Answers2

0

There are two reasons your code didn't work.

  1. The date() function formats the date (timestamp actually) provided. If a date is not provided then it generates a format based on todays date. So you needed to use something like mktime() or strtotime() to create the timestamp need for your due date.

  2. If you plan to use a string compare to determine if a date is in the future then you must use a sortable format such as Y-m-d.

A version of your code with these issues corrected could look something like this:

  date_default_timezone_set("America/New_York");
  $today = date("Y-m-d");

  $dueDate = date("Y-m-d", strtotime("05-08-21"));

  if ($dueDate > $today) {
     echo "<p> Success!";
  }
  else {
     echo "<p> Failure!";
  }

Note: I used the date as you had formatted it "05-08-21" which will result in the date being August 5th. If you really meant May 8th then change the string to use slashes ("05/08/21") instead of dashes.

Relevant documentation:

https://www.php.net/manual/en/function.strtotime.php https://www.php.net/manual/en/function.date.php

paul tracy
  • 81
  • 3
0

There are several reasons your method is not working:

  • date("05-08-21"); is not a valid use of the function. To return a formatted date for this date, you would run something like this:

date('m-d-y', strtotime('05-08-21'));

  • In order to compare the dates, they either need to be declared as a date object using the DateTime class, or, converted to a timestamp using strtotime

The modern way to achieve this is to use the DateTime class like so

// Define the format
$format = "m-d-y";

// Create the date objects
$today    = new \DateTime();
$dueDate  = \DateTime::createFromFormat($format, "05-08-21");

// Then you can run your condition...
if ($dueDate > $today) {
    echo "<p>Success!</p>";
} else {
    echo "<p>Failure!</p>";
}
Ben Carey
  • 16,540
  • 19
  • 87
  • 169