293

Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
HyderA
  • 20,651
  • 42
  • 112
  • 180

25 Answers25

563

You could also take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
    //$value->format('Y-m-d')       
}
Yasar Arafath
  • 605
  • 1
  • 9
  • 30
ViNce
  • 5,670
  • 1
  • 14
  • 2
  • 4
    Because ...it's only available from PHP 5 >= 5.3.0 – Tarek Aug 08 '12 at 14:22
  • 24
    Note that this doesn't _quite_ get you an array of `DateTime` objects; it gets you a `DatePeriod` object that implements the `Traversable` interface. If you were just planning on iterating over a list of dates with `foreach`, great; but otherwise, you'll need to use `foreach` anyway, in order to build your own array. – Aaron Adams Apr 26 '13 at 03:18
  • 65
    …Or, as it turns out, you can use `iterator_to_array($period)` to get your array. This function is available in all PHP versions where `DateInterval` is available. – Aaron Adams Apr 26 '13 at 03:25
  • 38
    `foreach( $period as $date) { $array[] = $date->format('Y-m-d'); }` will produce the required array. – Naveed May 14 '13 at 09:10
  • 20
    Despite the fact it's a nice piece of code, `DatePeriod` class excludes the end date. The `$period` would not include '2010-10-05'. You can exclude the start date with the 4th parameter `DatePeriod::EXCLUDE_START_DATE`. In the end, it does not even return an array of strings (as asked). Great answer, but to the wrong question. – Maxime Jul 08 '13 at 16:00
  • 1
    @Maxime: I agree with you, this answer is not complete; but it is starting point. [Bellow I answered where range works in both directions + it works on PHP >= 5.2.2.](http://stackoverflow.com/a/21073726/67332) – Glavić Jan 14 '14 at 22:55
  • 1
    How to include start and end date in array – عثمان غني Jun 16 '14 at 13:03
  • 5
    This code does not produce correct result... The last date is not included in the DatePeriod dates, i don't know why! Could you help me? – Elias Soares Sep 02 '14 at 18:56
  • 22
    To include the end date you need to add the time e.g. `new DateTime('2010-10-05 23:59:59')` – James F Aug 12 '15 at 09:20
  • Its not a big deal, just add a day to your enddate.. – M H Aug 07 '17 at 17:30
  • 8
    to include the `end date` in the result just use: $end_date = new DateTime($end.' +1 day'); – Alex Oct 26 '17 at 10:27
161
function createDateRangeArray($strDateFrom,$strDateTo)
{
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing
    // that in the main script

    $aryRange = [];

    $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
    $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));

    if ($iDateTo >= $iDateFrom) {
        array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo) {
            $iDateFrom += 86400; // add 24 hours
            array_push($aryRange, date('Y-m-d', $iDateFrom));
        }
    }
    return $aryRange;
}

source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

Quentin
  • 2,529
  • 2
  • 26
  • 32
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
  • 1
    make it recursive `if ($iDateTo>=$iDateFrom){... }else{ return $this->createDateRangeArray($strDateTo, $strDateFrom); }` – levye May 27 '16 at 10:14
  • This appears to add an extra date at the end of the array when spanning the Sunday - Monday of fall daylight savings time. – Chris Nov 03 '16 at 05:12
  • fail with example: `createDateRangeArray('2016-10-30','2016-11-01')` – Kelvin Nov 24 '16 at 07:00
  • @Kelvin I just tested `createDateRangeArray('2016-10-30','2016-11-01')` and it outputs the correct three dates. Can you provide an online demo to prove this failure? – mickmackusa Mar 02 '17 at 22:31
  • @Chris can you provide an online demo to prove this answer fails when handling DST-related date? – mickmackusa Mar 02 '17 at 22:33
  • @mickmackusa http://sandbox.onlinephpfunctions.com/code/c5d06d17d6a2733ddd0f4f80bd9b7286534006e8 If you comment timezone set function, output correct. I don't know why – Kelvin Mar 03 '17 at 03:59
  • @Kelvin Gee that's a good catch! I wanted to make sure mine didn't break ( http://stackoverflow.com/a/42558584/2943403 ) -- all good. It seems due to this failure, this answer should not have the green tick. – mickmackusa Mar 03 '17 at 04:07
  • 1
    A way to fix the extra day when spanning DST, would be to check again before the push `if($iDateFrom<=$iDateTo { /* push to $aryRange */ }`. This because the hours addition would move $iDateFrom beyond $iDateTo on some of the servers I've tested this on. – FiddlingAway Oct 31 '17 at 09:57
  • it is including +1 day on daylight saving clock – Saeed Vaziry Sep 21 '20 at 08:06
142

This is very very flexible.

/**
 * Creating date collection between two dates
 *
 * <code>
 * <?php
 * # Example 1
 * date_range("2014-01-01", "2014-01-20", "+1 day", "m/d/Y");
 *
 * # Example 2. you can use even time
 * date_range("01:00:00", "23:00:00", "+1 hour", "H:i:s");
 * </code>
 *
 * @author Ali OYGUR <alioygur@gmail.com>
 * @param string since any date, time or datetime format
 * @param string until any date, time or datetime format
 * @param string step
 * @param string date of output format
 * @return array
 */
function date_range($first, $last, $step = '+1 day', $output_format = 'd/m/Y' ) {

    $dates = array();
    $current = strtotime($first);
    $last = strtotime($last);

    while( $current <= $last ) {

        $dates[] = date($output_format, $current);
        $current = strtotime($step, $current);
    }

    return $dates;
}
alioygur
  • 5,324
  • 5
  • 35
  • 37
  • 1
    Watch for the `format` parameter that is only used for the output. This means that your input dates may have nothing to do with the `format` used as a parameter. – Maxime Dec 02 '14 at 13:49
  • @Maxime you right. i will update the documantation. – alioygur Dec 03 '14 at 14:04
  • 2
    Absolutely simple and brilliant! I'd love to see a web request memory and speed comparison between this solution and the object oriented one. – Dario Fumagalli Jul 09 '17 at 16:55
  • 1
    Beware of strtotime(). While it worked correctly for normal years, in my case it didn't include the last date when calculating within leap years. I assume this has to do with the extra day within February. – Alex Oct 16 '19 at 10:39
  • This sample doesn't support next scenarios: 1. `$first = '2020-11-26'; $last = '2020-11-26';` 2. `$first = '2020-11-26 13:00:00'; $last = '2020-11-26 14:00:00';` – М.Б. Nov 26 '20 at 15:52
45

Note that the answer provided by ViNce does NOT include the end date for the period.

If you are using PHP 5.3+, your best bet is to use a function like this:

/**
 * Generate an array of string dates between 2 dates
 *
 * @param string $start Start date
 * @param string $end End date
 * @param string $format Output format (Default: Y-m-d)
 *
 * @return array
 */
function getDatesFromRange($start, $end, $format = 'Y-m-d') {
    $array = array();
    $interval = new DateInterval('P1D');

    $realEnd = new DateTime($end);
    $realEnd->add($interval);

    $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

    foreach($period as $date) { 
        $array[] = $date->format($format); 
    }

    return $array;
}

Then, you would call the function as expected:

getDatesFromRange('2010-10-01', '2010-10-05');

Run demo

Note about DatePeriod class: You can use the 4th parameter of DatePeriod to exclude the start date (DatePeriod::EXCLUDE_START_DATE) but you cannot, at this time, include the end date.

Maxime
  • 8,645
  • 5
  • 50
  • 53
  • 1
    Please do not edit other answers to promote yours. It might be ok to add a comment to the answer. – Chronial Jul 09 '13 at 12:50
  • 4
    I used the provided code that was upvoted by the community and took time to debug and figure out why it was not working. The goal was to avoid other users to spend time on a "nice piece of code" that is not working and provide a real and full answer. It's just sad my edit was removed in an upvoted answer that misleads the community as people upvote without testing. It was not about MY answer, it was about THE answer. Anyway... – Maxime Jul 10 '13 at 13:22
  • I am sorry if I offended you. It is great the you want to improve the quality of the answers. Editing an answer to link to anther one is just not the way it is done on SO. You are always welcome to edit somebodys answer to improve it, though. – Chronial Jul 10 '13 at 14:04
  • You did not offend me. I think we have the same goal: helping others get their answer. I thought it was the best way but SO don't think so. I was uncomfortable changing (as it's not a simple edit) the whole answer written by someone else. No hard feelings here. We're good! :-) – Maxime Jul 10 '13 at 15:04
  • This is awesome, but when I modify to allow you to pass the interval, for example months, it returns an extra month due to the $realEnd->Add, I wish there was a reusable way to make this a universal date range function. – M H Jan 29 '16 at 14:15
22

Simple but like a charm:

    $period = new DatePeriod(new DateTime('2015-01-01'), new DateInterval('P1D'), new DateTime('2015-01-15 +1 day'));
    foreach ($period as $date) {
        $dates[] = $date->format("Y-m-d");
    }

    //ONLY SHOWING
    echo '<pre>';
    var_dump($dates);
    echo '</pre>';
    exit();
Victor Azevedo
  • 537
  • 4
  • 7
19
  function GetDays($sStartDate, $sEndDate){  
      // Firstly, format the provided dates.  
      // This function works best with YYYY-MM-DD  
      // but other date formats will work thanks  
      // to strtotime().  
      $sStartDate = gmdate("Y-m-d", strtotime($sStartDate));  
      $sEndDate = gmdate("Y-m-d", strtotime($sEndDate));  

      // Start the variable off with the start date  
     $aDays[] = $sStartDate;  

     // Set a 'temp' variable, sCurrentDate, with  
     // the start date - before beginning the loop  
     $sCurrentDate = $sStartDate;  

     // While the current date is less than the end date  
     while($sCurrentDate < $sEndDate){  
       // Add a day to the current date  
       $sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));  

       // Add this new day to the aDays array  
       $aDays[] = $sCurrentDate;  
     }  

     // Once the loop has finished, return the  
     // array of days.  
     return $aDays;  
   }  

use like

GetDays('2007-01-01', '2007-01-31'); 
Hissvard
  • 488
  • 7
  • 24
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
16

You must add $end->modify('+1 day') to include last day of interval, for example the January will have a 31 days instead of 30 without using modify() method. This version of code will include the last day of the interval:

$begin = new DateTime( '2018-08-01' );
$end = new DateTime( '2018-08-31' );
$end = $end->modify( '+1 day' ); 

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
    echo $date->format("Ymd") . "<br>";
}

PHP doc link

Alex Joe
  • 369
  • 3
  • 8
13

This is short, sweet, and should work in PHP4+.

function getDatesFromRange($start, $end){
    $dates = array($start);
    while(end($dates) < $end){
        $dates[] = date('Y-m-d', strtotime(end($dates).' +1 day'));
    }
    return $dates;
}
drolex
  • 4,993
  • 1
  • 18
  • 14
  • Unfortuanately this neat solution add one day too much... – Peavey Oct 16 '14 at 16:24
  • 1
    Peavey, no it doesn't... – drolex Oct 21 '14 at 07:47
  • 1
    This solution is great as long as you don't care that it will inevitably run too long and cause the script to run until max_execution_time has been reached. – dctucker Aug 03 '15 at 17:55
  • 1
    dctucker, sounds like you invented a problem. – drolex Aug 14 '15 at 08:39
  • dctucker is right.. This what I'm getting from this function "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)" – M_R_K Feb 12 '16 at 12:12
  • You must have done something wrong. Multiple people say it works. – drolex Feb 20 '16 at 05:22
  • I like this one as it's clean and simple, don't have to use a class, wonder if it's faster than the top answer which uses DatePeriod class? – drooh Feb 01 '18 at 21:03
11

Short function. PHP 5.3 and up. Can take optional third param of any date format that strtotime can understand. Automatically reverses direction if end < start.

function getDatesFromRange($start, $end, $format='Y-m-d') {
    return array_map(function($timestamp) use($format) {
        return date($format, $timestamp);
    },
    range(strtotime($start) + ($start < $end ? 4000 : 8000), strtotime($end) + ($start < $end ? 8000 : 4000), 86400));
}

Test:

date_default_timezone_set('Europe/Berlin');
print_r(getDatesFromRange( '2016-7-28','2016-8-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-28' ));
print_r(getDatesFromRange( '2016-10-28','2016-11-2' ));
print_r(getDatesFromRange( '2016-11-2','2016-10-28' ));
print_r(getDatesFromRange( '2016-4-2','2016-3-25' ));
print_r(getDatesFromRange( '2016-3-25','2016-4-2' ));
print_r(getDatesFromRange( '2016-8-2','2016-7-25' ));
print_r(getDatesFromRange( '2016-7-25','2016-8-2' ));

Output:

Array ( [0] => 2016-07-28 [1] => 2016-07-29 [2] => 2016-07-30 [3] => 2016-07-31 [4] => 2016-08-01 [5] => 2016-08-02 ) 
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 ) 
Array ( [0] => 2016-10-28 [1] => 2016-10-29 [2] => 2016-10-30 [3] => 2016-10-31 [4] => 2016-11-01 [5] => 2016-11-02 ) 
Array ( [0] => 2016-11-02 [1] => 2016-11-01 [2] => 2016-10-31 [3] => 2016-10-30 [4] => 2016-10-29 [5] => 2016-10-28 ) 
Array ( [0] => 2016-04-02 [1] => 2016-04-01 [2] => 2016-03-31 [3] => 2016-03-30 [4] => 2016-03-29 [5] => 2016-03-28 [6] => 2016-03-27 [7] => 2016-03-26 [8] => 2016-03-25 ) 
Array ( [0] => 2016-03-25 [1] => 2016-03-26 [2] => 2016-03-27 [3] => 2016-03-28 [4] => 2016-03-29 [5] => 2016-03-30 [6] => 2016-03-31 [7] => 2016-04-01 [8] => 2016-04-02 ) 
Array ( [0] => 2016-08-02 [1] => 2016-08-01 [2] => 2016-07-31 [3] => 2016-07-30 [4] => 2016-07-29 [5] => 2016-07-28 [6] => 2016-07-27 [7] => 2016-07-26 [8] => 2016-07-25 ) 
Array ( [0] => 2016-07-25 [1] => 2016-07-26 [2] => 2016-07-27 [3] => 2016-07-28 [4] => 2016-07-29 [5] => 2016-07-30 [6] => 2016-07-31 [7] => 2016-08-01 [8] => 2016-08-02 )
nzn
  • 1,014
  • 11
  • 20
8

Here is a function, that will return date ranges in both directions and it works on PHP >=5.2.2 :

function createRange($start, $end, $format = 'Y-m-d') {
    $start  = new DateTime($start);
    $end    = new DateTime($end);
    $invert = $start > $end;

    $dates = array();
    $dates[] = $start->format($format);
    while ($start != $end) {
        $start->modify(($invert ? '-' : '+') . '1 day');
        $dates[] = $start->format($format);
    }
    return $dates;
}

Use example:

print_r(createRange('2010-10-01', '2010-10-05'));
/*Array
(
    [0] => 2010-10-01
    [1] => 2010-10-02
    [2] => 2010-10-03
    [3] => 2010-10-04
    [4] => 2010-10-05
)*/

print_r(createRange('2010-10-05', '2010-10-01', 'j M Y'));
/*Array
(
    [0] => 5 Oct 2010
    [1] => 4 Oct 2010
    [2] => 3 Oct 2010
    [3] => 2 Oct 2010
    [4] => 1 Oct 2010
)*/

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
8

many ways of getting this done, but finally it all depends on PHP version you are using. Here is summary of all solutions:

get PHP version:

echo phpinfo();

PHP 5.3+

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

PHP 4+

/**
 * creating between two date
 * @param string since
 * @param string until
 * @param string step
 * @param string date format
 * @return array
 * @author Ali OYGUR <alioygur@gmail.com>
 */
function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) { 

    $dates = array();
    $current = strtotime($first);
    $last = strtotime($last);

    while( $current <= $last ) { 

        $dates[] = date($format, $current);
        $current = strtotime($step, $current);
    }

    return $dates;
}

PHP < 4

you should upgrade :)

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
  • The PHP 5.3+ solution does not return all dates and not in the expected way (array of strings). The PHP 4+ is misleading as the `format` parameter is only used in the output (and not in input parameters). – Maxime Dec 02 '14 at 13:44
  • I agree with Maxime. the PHP 5.3+ approach declares `$period` as an object that is positively bloated and useless for this case. There is absolutely no date range array generated. http://sandbox.onlinephpfunctions.com/code/a8bf2ac01f79691a3f7ad34d14314fdf8a41445b Downvoted until corrected. On this page there are sleeker functions available compared to `PHP 4+ dateRange()`. – mickmackusa Mar 03 '17 at 04:43
5
// Specify the start date. This date can be any English textual format  
$date_from = "2018-02-03";   
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp  

// Specify the end date. This date can be any English textual format  
$date_to = "2018-09-10";  
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp  

// Loop from the start date to end date and output all dates inbetween  
for ($i=$date_from; $i<=$date_to; $i+=86400) {  
    echo date("Y-m-d", $i).'<br />';  
} 
Nirav Bhoi
  • 559
  • 9
  • 17
4

Solution for PHP 5.2 with DateTime objects. But startDate MUST be before endDate.

function createRange($startDate, $endDate) {
    $tmpDate = new DateTime($startDate);
    $tmpEndDate = new DateTime($endDate);

    $outArray = array();
    do {
        $outArray[] = $tmpDate->format('Y-m-d');
    } while ($tmpDate->modify('+1 day') <= $tmpEndDate);

    return $outArray;
}

Using:

$dates = createRange('2010-10-01', '2010-10-05');

$dates contain:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )       
cubaguest
  • 544
  • 4
  • 8
4
<?
print_r(getDatesFromRange( '2010-10-01', '2010-10-05' ));

function getDatesFromRange($startDate, $endDate)
{
    $return = array($startDate);
    $start = $startDate;
    $i=1;
    if (strtotime($startDate) < strtotime($endDate))
    {
       while (strtotime($start) < strtotime($endDate))
        {
            $start = date('Y-m-d', strtotime($startDate.'+'.$i.' days'));
            $return[] = $start;
            $i++;
        }
    }

    return $return;
}
Gazler
  • 83,029
  • 18
  • 279
  • 245
3

Here's a way of doing this using Carbon https://github.com/briannesbitt/Carbon:

public function buildDateRangeArray($first, $last)
{
    while ($first <= $last) {
        $dates[] = $first->toDateString();

        $first->addDay();
    }

    return $dates;
}

This, of course, can be tweaked to not use Carbon. The $first and $last parameters passed to the function are Carbon instances.

Gareth Daine
  • 4,016
  • 5
  • 40
  • 67
3
$report_starting_date=date('2014-09-16');
$report_ending_date=date('2014-09-26');
$report_starting_date1=date('Y-m-d',strtotime($report_starting_date.'-1 day'));
while (strtotime($report_starting_date1)<strtotime($report_ending_date))
{

    $report_starting_date1=date('Y-m-d',strtotime($report_starting_date1.'+1 day'));
    $dates[]=$report_starting_date1;
  } 
  print_r($dates);

 // dates    ('2014-09-16', '2014-09-26')


 //print result    Array
(
[0] => 2014-09-16
[1] => 2014-09-17
[2] => 2014-09-18
[3] => 2014-09-19
[4] => 2014-09-20
[5] => 2014-09-21
[6] => 2014-09-22
[7] => 2014-09-23
[8] => 2014-09-24
[9] => 2014-09-25
[10] => 2014-09-26
)
Anandha Mariappan A
  • 601
  • 1
  • 6
  • 10
  • Please edit your answer and give more details what ou are doing and correct the formatting. – bish Jul 18 '15 at 05:57
3
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax

$range = array();

if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);

if ($start > $end) return createDateRangeArray($end, $start);

do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start < $end);

return $range;
} 

Source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

TigerTiger
  • 10,590
  • 15
  • 57
  • 72
2
// will return dates array
function returnBetweenDates( $startDate, $endDate ){
    $startStamp = strtotime(  $startDate );
    $endStamp   = strtotime(  $endDate );

    if( $endStamp > $startStamp ){
        while( $endStamp >= $startStamp ){

            $dateArr[] = date( 'Y-m-d', $startStamp );

            $startStamp = strtotime( ' +1 day ', $startStamp );

        }
        return $dateArr;    
    }else{
        return $startDate;
    }

}

returnBetweenDates( '2014-09-16', '2014-09-26' );

// print_r( returnBetweenDates( '2014-09-16', '2014-09-26' ) );

it will return array like below:

Array
(
    [0] => 2014-09-16
    [1] => 2014-09-17
    [2] => 2014-09-18
    [3] => 2014-09-19
    [4] => 2014-09-20
    [5] => 2014-09-21
    [6] => 2014-09-22
    [7] => 2014-09-23
    [8] => 2014-09-24
    [9] => 2014-09-25
    [10] => 2014-09-26
)
ashu joshi
  • 29
  • 2
  • Could you show your output as well, please to demonstrate that your code works as expected. – kkuilla Oct 01 '14 at 11:04
  • Thanks for showing your interest. This funtion returns array, you can check as i edit the answer with output. – ashu joshi Oct 04 '14 at 04:55
  • 1
    So what is the difference between your solution and e.g. @RobertPitt or HaimEvgi's answer? Why is this answer different to all the existing answers? It seems like this answer does not add anything new. You should only provide an answer if you add new knowledge or provide a different solution to the problem. If you can't motivate what's new, please delete this answer but please don't be discouraged. [How-to-answer](http://stackoverflow.com/help/how-to-answer) might be useful in the future. – kkuilla Oct 06 '14 at 08:19
2

I think it's the shortest answer

Edit the code as you like

for ($x=strtotime('2015-12-01');$x<=strtotime('2015-12-30');$x+=86400)
echo date('Y-m-d',$x);
Mostafa
  • 909
  • 1
  • 7
  • 16
  • Not only does this not produce an array as requested in the question. This answer breaks when the timezone is set to ('Europe/Berlin') and the date range is 2016-10-30 to 2016-11-01. http://sandbox.onlinephpfunctions.com/code/81e57d49b072a63e729a2e5fff5235c8fa845d8f – mickmackusa Mar 03 '17 at 04:22
1

Here is the another solution. Please check this.

$first = '10/30/2017'; //starting date
$last= '10/11/2017';   //ending date
$first_time_arr=explode('/',$first); 
$last_time_arr=explode('/',$last);
//create timestamp of starting date
$start_timestamp=mktime(0,0,0, $first_time_arr[0], $first_time_arr[1],$first_time_arr[2]);
//create timestamp of ending date
$end_timestamp=mktime(0,0,0, $last_time_arr[0], $last_time_arr[1],$last_time_arr[2]);
$date_arr=array();
for($i=$start_timestamp;$i<=$end_timestamp;$i=$i+86400){
    $date_arr[]=date("Y-m-d",$i); //this will save all dates in array
}
Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
0
public static function countDays($date1,$date2)
{
    $date1 = strtotime($date1); // or your date as well
    $date2 = strtotime($date2);
    $datediff = $date1 - $date2;
    return floor($datediff/(60*60*24));
}

public static function dateRange($date1,$date2)
{
    $count = static::countDays($date1,$date2) + 1;
    $dates = array();
    for($i=0;$i<$count;$i++)
    {
        $dates[] = date("Y-m-d",strtotime($date2.'+'.$i.' days'));
    }
    return $dates;
}
johndavedecano
  • 522
  • 5
  • 11
0
function datesbetween ($date1,$date2)
{
    $dates= array();
    for ($i = $date1
       ; $i<= $date1
       ; $i=date_add($i, date_interval_create_from_date_string('1 days')) ) 
    {            
       $dates[] = clone $i;
    }
    return $dates;
}
David Newcomb
  • 10,639
  • 3
  • 49
  • 62
figuitiko
  • 44
  • 3
-2

To make Mostafa's answer complete, this is definietly the simplest and most efficient way to do it:

function getDatesFromRange($start_date, $end_date, $date_format = 'Y-m-d')
   {
      $dates_array = array();
      for ($x = strtotime($start_date); $x <= strtotime($end_date); $x += 86400) {
         array_push($dates_array, date($date_format, $x));
      }

      return $dates_array;
   }

   // see the dates in the array
   print_r( getDatesFromRange('2017-02-09', '2017-02-19') );

You can even change the default output date format if you add a third parameter when you call the function, otherwise it will use the default format that's been set as 'Y-m-d'.

I hope it helps :)

Fery Kaszoni
  • 3,956
  • 1
  • 18
  • 11
  • This answer breaks when the timezone is set to ('Europe/Berlin') and the date range is 2016-10-30 to 2016-11-01. http://sandbox.onlinephpfunctions.com/code/b57a6fdf07cce1cea791db1db14ed38f369d2299 – mickmackusa Mar 03 '17 at 04:24
-3
function getWeekdayDatesFrom($format, $start_date_epoch, $end_date_epoch, $range) {

    $dates_arr = array();

    if( ! $range) {
        $range = round(abs($start_date_epoch-$end_date_epoch)/86400) + 1;
    } else {
        $range = $range + 1; //end date inclusive
    }

    $current_date_epoch = $start_date_epoch;

    for($i = 1; $i <= $range; $i+1) {

        $d = date('N',  $current_date_epoch);

        if($d <= 5) { // not sat or sun
            $dates_arr[] = "'".date($format, $current_date_epoch)."'";
        }

        $next_day_epoch = strtotime('+'.$i.'day', $start_date_epoch);
        $i++;
        $current_date_epoch = $next_day_epoch;

    }

    return $dates_arr;
} 
womplefrog
  • 769
  • 1
  • 6
  • 18
  • This should answer the question, and then some. With this function you can declare the return format (i.e. Y-m-d), declare a start date and end date or a start date and range. I currently have it set to include the end date and it only returns weekdays by default (which can be easily undone). – womplefrog Nov 18 '13 at 14:31
  • An incorrect answer can, in many cases, be just as helpful as a correct one if a reason as to why it is wrong is given. If you're going to downvote, you should give a reason. However, my answer is not incorrect. It is also a fair answer. – womplefrog Oct 23 '14 at 21:08
  • This answer is doomed to fail when the timezone is set to Europe/Berlin and the date range is 2016-10-30 to 2016-11-01. Also, there is no function call which specifies the values to feed in for `$format`,`$start_date_epoch`,`$end_date_epoch`,`$range`. Please edit or delete this answer. – mickmackusa Mar 03 '17 at 04:32
-3
$arr = range(strtotime("2013-12-01"),strtotime("2013-12-31"), "86400");
array_walk_recursive($arr, function(&$element) { $element = date("Y-m-d", $element); });
print_r ($arr);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 4
    Please add some english to clarify your answer. – hgwhittle Dec 20 '13 at 15:46
  • This answer breaks when the timezone is set to ('Europe/Berlin') and the date range is 2016-10-30 to 2016-11-01. http://sandbox.onlinephpfunctions.com/code/db3881a8ecab7dc9a6bcf63bf87f404cefdb2bcc – mickmackusa Mar 03 '17 at 04:17