0

I’m trying to compare two dates (the current date with an ACF datepicker one) to display specific content. What I’m trying to achieve is to display a phrase if the ACF date is lower than the current time (in few words if a service is expired). This is my code:

$dataScadenza = get_field('data_di_scadenza');
$currentDateTime = date('d.m.y');

if($dataScadenza <= $currentDateTime) {

echo '<a href="'.get_field('link_esito').'">';
echo '<button class="vedi_esiti">VEDI ESITI</button>';
echo '</a>';

} else {

echo '<span class="ds_label">data scadenza</span>';
echo '<div class="ds_date">'.get_field('data_di_scadenza').'</div>';

}

where $dataScadenza is the ACF date and $currentDateTime is current date. Both variables have the same output (d.m.y).

What happens is that the comparison is applied only on day number and not on the entire date.

Anyone can help to solve the problem?

Thank you!

  • 1
    See this answer, it applies to your situation: stackoverflow.com/a/32642436/107244 – Michelle Jul 8 '19 at 15:39
  • Hello Michelle, thanks for the answer! I tried this approach but it doesn't seem to work. With new DateTime() I get all the services as expired even if they are not yet. Here's my code: $dataScadenza = new DateTime($dataScadenza); $currentDateTime = new DateTime(); if($dataScadenza <= $currentDateTime) { echo '<a href="'.get_field('link_esito').'">'; echo '<button class="vedi_esiti">VEDI ESITI</button>'; echo '</a>'; } else { echo '<span class="ds_label">data scadenza</span>'; echo '<div class="ds_date">'.get_field('data_di_scadenza').'</div>'; } – Stefano Jul 8 '19 at 16:03
  • 1
    Did you try changing your date formats to something that is string comparable, like Y-m-d ? – Michelle Jul 8 '19 at 16:32
  • 1
    d.m.y does not look like a valid date format for comparison. As Michelle said, convert it to something standard. See date_create_from_format(). – Max Yudin Jul 8 '19 at 16:56
  • Thank you for all the answers! I tried Y-m-d format and it works perfectly. Now my question is: how can I convert - after comparison - the date in d.m.y? Is it possible? – Stefano Jul 9 '19 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.