0

Im trying to create a conditional statement comparing two dates. I have a ACF custom date field as one date, and then comparing against the current date.

Below is what i have and iv echoed both $date and $currentdate and they both come out in the same format, so im not sure why it wont work. They both output in the format like: 20170105 which i beleive they need to be to compare.

<?php
    $currentdate = current_time('Ymd');
    $date = get_field('course_start_date', false, false);
    $date = new DateTime($date);


    if ($currentdate > $date) {
    echo ' - Started.';  
    } else {
      echo ' - Not started.';
    }
    ?>
5
  • Do an echo or do a print_r on $date and give the value please.
    – CodeMascot
    Jan 5, 2017 at 10:30
  • @the_dramatist sure. $currentdate = 20170105 and $date = 20170201. Obvious the $date changes depending on which post. But i have two posts, one where the $date is larger than $currentdate and one that is smaller than, but my conditional statement says the same
    – Futwill
    Jan 5, 2017 at 10:36
  • With those values, the conditional statement works as expected? Can you debug with real data that actually doesn't work? Which date format do you have in course_start_date? Why do you post in your comment integer values saying they are returned by current_time() and DateTime when those functions return strings? Please, edit the question to add additional information.
    – cybmeta
    Jan 5, 2017 at 10:56
  • I just tested this in my system and it worked as it is expected. Please show us what error your system is throwing ?
    – CodeMascot
    Jan 5, 2017 at 10:58
  • Ahh stupidly i removed the $date = new DateTime($date); line and that has resolved it. Sorry i mis-understood the ACF documentation clearly. Thanks for your help all
    – Futwill
    Jan 5, 2017 at 11:17

1 Answer 1

2

instead of $currentdate = current_time('Ymd');

you can use $currentdate = new DateTime();

so the Final Solution should be as like given below

<?php
    $currentdate = new DateTime();
    $date = get_field('course_start_date', false, false);
    $date = new DateTime($date);


    if ($currentdate > $date) {
    echo ' - Started.';  
    } else {
      echo ' - Not started.';
    }
    ?>
1
  • Please merge your two accounts
    – cjbj
    Jan 5, 2017 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.