0

Hi I'd like some help comparing dates. This is my code

date_default_timezone_set('Europe/London');

// get today's date
$datetoday = date('Y-m-d');

if ($datetoday > $pickup_date) {
array_push($errors, "this pickup date is invalid, it has already passed");  

The pickup date is a value I collect from a form, here is the code for the form:

<div class="input-group">
    <label>Pickup Date</label>
    <input type="date" name="pickup_date" >
</div>

what I want is for the user to not be able to set the pickup date to a date which has already gone. My system is a booking system. They should be only able to set dates which are after today's date.

But this current code does not work, it still allows the user to book dates before and after today's date. I've even tried switching the comparison operators around where it compares the dates.

Thanks all help is appreciated.

miken32
  • 42,008
  • 16
  • 111
  • 154
copmachine
  • 11
  • 1
  • 3
  • 1
    What is the format of `$pickup_date`? To troubleshoot, you might try outputting both values: `var_dump($datetoday); var_dump($pickup_date);`. – showdev Mar 11 '20 at 19:30
  • Also you probably want `date('Ymd')` or just use `time()` and convert the form date to a timestamp with `strtotime()`. – AbraCadaver Mar 11 '20 at 19:46
  • Given that the default format for the [value](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Value) of `` is "YYYY-MM-DD", here's a [demonstration of the working string comparison](http://sandbox.onlinephpfunctions.com/code/1c239cef4ba00d8013224635804fa8e5bee33ace). – showdev Mar 11 '20 at 20:50

1 Answers1

2

You are not comparing dates, you are comparing strings. Try using DateTime objects instead:

date_default_timezone_set('Europe/London');

$pickup_date = \DateTime::createFromFormat('Y-m-d', $_POST['pickup_date']);

// get today's date
$datetoday = \DateTime::create('midnight');

if ($datetoday > $pickup_date) {
    array_push($errors, "this pickup date is invalid, it has already passed");
}
miken32
  • 42,008
  • 16
  • 111
  • 154
  • 1
    I agree this is great advice, but comparing two strings of that same format [should work too](https://stackoverflow.com/a/2114029/924299). – showdev Mar 11 '20 at 19:51