0

I have a ajax data object that comers in with $startDate which is Nov 12, 2013 and a $endDate which is January 31, 2014 and I would like to create an array that looks like:

array(2013-11-12, 2013-11-13, 2013-11-14, ... , 2014-01-31);

The way I attempted to do this was:

    while($startDate < $endDate){
       $day = gmdate('Y-m-d', strtotime('+1 day', strtoTime($data->data['startDate'])));
       $daysOfTheWeek[] = $day;
    }

But the script timed out after 30 seconds. So I am wondering what the proper way to do this is.

LogicLooking
  • 916
  • 1
  • 16
  • 32
  • `set_time_limit(0);` But oh, that's an infinite loop. Don't crash your server – Hanky Panky Nov 14 '13 at 17:34
  • Look into the `DateInterval` class: http://us1.php.net/dateinterval – pgl Nov 14 '13 at 17:35
  • You're never changing startdate, so why do you expect it to ever be anything but less than enddate? Permanent loop – Mark Baker Nov 14 '13 at 17:36
  • 1
    [php-return-all-dates-between-two-dates-in-an-array](http://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array) – Mithun Satheesh Nov 14 '13 at 17:36
  • If you use php 5.3 look for datetime object there is a diff method that return a datetimeinterval objet you can format with format method. – SmasherHell Nov 14 '13 at 17:41

2 Answers2

1
<?php
  $dates=array();
  $start=strtotime("Nov 12, 2013");
  $end=strtotime("January 31, 2014");
  while($start <= $end)
  {
    $dates[]=date("Y-m-d",$start);
    $start=strtotime("+1 day",$start);
  }
  print_r($dates);
?>

Fiddle

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
1
date_default_timezone_set('UTC');
$date_from = 'Nov 12, 2013';
$date_to = 'January 31, 2014';
$date_range = array_map(function ($date) {
        return $date->format('Y-m-d');
    }, iterator_to_array(
        new DatePeriod(new DateTime($date_from),
                       DateInterval::createFromDateString('+1 day'),
                       (new DateTime($date_to))->modify('+1 day'))));
var_dump($date_range);

Demo: https://eval.in/68133

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96