Support

Account

Home Forums Backend Issues (wp-admin) How To Get Soonest Date From DateTime Picker

Solved

How To Get Soonest Date From DateTime Picker

  • I’ve got a custom post type of ‘event’ that has a ‘event_start_date’ field using the Date Time Picker Field type. The return value is set to:
    November 19, 2021 2:41 pm : F j, Y g:I a

    I’m trying query all events and get the next upcoming event (that’s not already happened).

    This query is working to get all upcoming events and excludes past events.

    Inside the loop I’m trying to add all the date to a date array. Then. I want to find which of these events is the next one scheduled and store stat date.

    
    $today = date('Ymd');
    
    // Arguments for the query
    $args = array(
      'post_type' => 'event',
      'posts_per_page' => -1,
      'post_status' => 'publish',
      'meta_query' => array(
        array(
          'key' => 'event_start_date',
          'value' => $today,
          'type' => 'DATE',
          'compare' => '>='
        )
      ),
      'meta_key' => 'event_start_date',
      'orderby' => 'meta_value_num',
      'order' => 'ASC',
    );
    
    $events = new WP_Query( $args );
    
    if( $events->have_posts() ):
    
      $dates = array();
    
      while( $events->have_posts() ):
        $events->the_post();
        $event_start_date = get_field('event_start_date');
        $dates[] = $event_start_date;
    
      endwhile;
    
      print_r($dates);
      echo "<p class='white'>Max Date: ". max(array_values($dates))."</p>";
      echo "<p class='white'>Min Date: ". min(array_values($dates))."</p>";
    
      wp_reset_postdata();
    
    endif;
    

    I’m trying to use the min(array_values($dates)) to find the soonest date in the array.

    Once I have that Date. How can I parse the values to get a couple different formats:

    $dateMDY = …;// November 19, 2021
    $Time = …; // 12:00 am
    $counterDate = … ;// Jan 5, 2022 15:37:25

    Thanks and any help would be greatly appreciated 🙂

  • Also… one of the date formats I need is to be able to work with this snippet:

    
    var countDownDate = new Date("Jan 5, 2022 15:37:25").getTime();
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.