1

I have a custom-post-type for Vacationperiods where there are some custom fields of type Datepicker to set start and end date. Now I want to get all the days between these to dates and add them to an array.

function get_vacation_dates(){
global $post;

  $args = array(
    'post_type' => array('vacationperiods'),
    'post_status' => array('publish'),
    'order' => 'ASC'
  );

  $posts = get_posts($args);
  $vac = [];
  foreach ($posts as $post){

    $vacationTitle = get_field('name', $post->ID);
    $startDate = get_field('vacation_start', $post->ID);
    $endDate = get_field('vacation_end', $post->ID);

    // GET ALL DAYS/DATES
    for ($i=$startDate; $i<=$endDate; $i+=86400) {  
        $days = date('Y-m-d', $i);
    }       

    $duration = dateDiff($startDate, $endDate);

    $vac[] = [
        'name' => $vacationTitle,
        'start' => $startDate,
        'end' => $endDate,
        'duration' => $duration,
        'days' => $days
    ];



  }

  echo json_encode($days);

  die();
}

This approach does not work, it gives me "days: '1970-01-01'" - but as mentioned before I want to get all days listed as an array, something like "days: ['2018-09-13', '2018-09-14', etc..]

How can I achieve that?

1
  • 2
    convert date into strtotime. Commented Sep 13, 2018 at 8:06

1 Answer 1

3

The strtotime() function parses an English textual DateTime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Something like this:

$days = array();
    // GET ALL DAYS/DATES
        for ($i=strtotime($startDate); $i<=strtotime($endDate); $i+=86400) {  
            $days[] = date('Y-m-d', $i);
        } 
Sign up to request clarification or add additional context in comments.

6 Comments

For some reason, this only gives me the endDate as result :-/
Do you mean last date of loop?
Yes exactly, the last date of loop
Actually, $days is a variable. it overrides with last value. It should be define an array or as you want.
Define $days as an array $days = array();. see updated answer.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.