0

I'm trying to cycle through some dates in this format: "May 10, 2016" and see if today is before or after that, for the purpose of showing/hiding div's associated with that date.

I've searched so far, and only found questions where the comparison is just with numerical dates, but what would be the correct code for this sort of comparison:

$cDate = "May 10, 2016"
$todayDate = NOW(); // in "May 25, 2016" format
if ($cDate < $todayDate) {
    ...more code...
}
LatentDenis
  • 2,839
  • 12
  • 48
  • 99
  • 1
    http://www.php.net/manual/en/class.datetime.php http://carbon.nesbot.com/docs/ (and `NOW()` is MySQL, PHP uses `time()`). – ceejayoz May 25 '16 at 13:56
  • 1
    That's because date strings don't exist; they are simply strings that we humans interpret as a date, but are nothing more than sequences of characters to a computer.... that's why you can't compare date strings, but only numeric dates – Mark Baker May 25 '16 at 13:57
  • 1
    It isn't appropriate for you to be asking answerers of your question to up vote. – vascowhite May 25 '16 at 14:24
  • @vascowhite Sorry, will keep in mind going forward. – LatentDenis May 25 '16 at 16:16

3 Answers3

3

Solution is simple with PHP's DateTime() class.

<?php
    $date = new DateTime('May 30, 2016');
    $today = new DateTime();

    if($today > $date) {
        echo "Date was in past";
    } else if ($today == $date) {
        echo "It's now";
    } else {
        echo "Date is in future";
    }
hypeJunction
  • 351
  • 1
  • 9
Rehmat
  • 4,681
  • 3
  • 22
  • 38
2

If you don't care about timezones:

$that = strtotime("May 10, 2016");
$now = time();
if ($that < $now) {
  // do your thing
}
hypeJunction
  • 351
  • 1
  • 9
1

It's easy with strtotime()

$cDate = "May 10, 2016";
$todayDate = strtotime(date('Y-m-d')); // in "May 25, 2016" format
if (strtotime($cDate) < $todayDate) {
    echo 'hi';
}
Mojtaba
  • 4,852
  • 5
  • 21
  • 38