Get only the next date from multiple dates

I have several dates, some of the past, some of the future, and I want to show only the next date in the future of this list. If there is no date in the future, I want to echo some text.

I am using ACF Date Picker inside a Repeater. First of all, I think I have to get the current date, to compare it with the others:

Read More
date_default_timezone_set('Europe/Berlin');
$date = date('Ymd', time());

I chose the Ymd format because the repeater outputs the dates the exact same way. Now I need to check somehow all subfields inside my repeater. I guess this is done using somehow like

$rows = get_field('repeater_field_name');
if($rows) {
  foreach($rows as $row) {
     // compare the dates, choose only the next coming date
     // dates are stored in the_sub_field('repeater_date_field');
  }
}

How can I get all the_sub_field('repeater_date_field') of my get_field('repeater_field_name') values? And how can I detect its row (for adding other sub fields to the same row)?

Related posts

2 comments

  1. You can store your all dates in array. Then sort it in ascending order. Then take the first date from the list which is greater than today.

    Please look into below code.

    date_default_timezone_set('Europe/Berlin');
    $date = date('Ymd', time());
    
    $dates = array();
    $rows = get_field('repeater_field_name');
    if($rows) {
      foreach($rows as $row) {
          $dates[] = $row->date_field;
         // compare the dates, choose only the next coming date
         // dates are stored in the_sub_field('repeater_date_field');
    
      }
    }
    sort($dates);
    $final_date = "";
    foreach($dates as $date_row){
        if($date_row > $date){
            $final_date = $date_row;
            return true;
        }
    }
    echo $final_date;
    
  2. You can compare 2 date to solve this problem. For example

    $date_bef = strtotime("151218"); // December 18, 2015
    $date_after = strtotime("151219"); // December 19, 2015
    if($date_after - $date_bef == 1)
    echo "This is a next day";
    

    If you don’t want compare, you can add 1 day to existing time, example

    $next_day = date("Ymd",strtotime("151220") + 60*60*24);
    

Comments are closed.