Support

Account

Home Forums General Issues Comparing Dates

Solving

Comparing Dates

  • Hey guys, I’m trying to compare ACF inserted date with actual date, but no success. Any ideas on how to do this?

    Below code doesn’t work:
    <?php
    $date = get_field(‘data_de_entrega’);
    $now = new DateTime();

    if($date < $now) {
    echo ‘date is in the past’
    ;
    }
    ?>

  • In order to compare them this way you need to convert the field to a unix time value. The return value of the field needs to be in a format that will be recognized by strtotime()
    see http://php.net/manual/en/function.strtotime.php
    and http://php.net/manual/en/datetime.formats.php

    
    $time = strtotime(get_field('date_field_name'));
    $now = time();
    if ($time < $now) {
      // .....
    }
    

    Edit:

    Also, new DateTime() creates a date/time object which cannot be compared to a string. It may be possible to use this object but it will take a lot more code to extract the string you want from it. I can’t help you with that because I personally use the simpler functions for dates and time rather than using this object.

  • Try this:

    $date1=date(‘d/m/y’);
    $tempArr=explode(‘_’, ’31_12_11′);
    $date2 = date(“d/m/y”, mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));
    You can then perform the strtotime() method to get the difference.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Comparing Dates’ is closed to new replies.