PHP: Return all dates between two dates in an arra

2018-12-31 03:20发布

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' )

27条回答
怪性笑人.
2楼-- · 2018-12-31 03:57

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.

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 03:57

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
}
查看更多
墨雨无痕
4楼-- · 2018-12-31 03:58

look on this

  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'); 
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 03:59

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

查看更多
浪荡孟婆
6楼-- · 2018-12-31 03:59
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;
}
查看更多
梦醉为红颜
7楼-- · 2018-12-31 04:00

I love a solid one-liner!

My php discovery of the day was that array_push() returns the new number of elements in the array.

I managed to check for the end date match, increment $x, and push new elements all within the two-part condition statement of an empty while loop.

function getDatesFromRange($a,$b,$x=0,$dates=[]){
    while(end($dates)!=$b && $x=array_push($dates,date("Y-m-d",strtotime("$a +$x day"))));
    return $dates;
}
var_export(getDatesFromRange('2010-10-01','2010-10-05'));

The most similar function to mine on this page is drolex's (which I didn't actually find until after I wrote mine, if you believe me). I did some speed tests across large and small date ranges and they seem to beat each other just as often -- so I'm calling them equal performers. Here are some other comparisons:

  • We both use date(), strtotime(), and two array functions.
  • Drolex uses just three variables, I use the same three plus $x.
  • Because loading the start date into the $date array is not necessary for my function, I can declare it in the function parameters and spare the line (likewise with $x).

**Just a couple of important notes:

1- Date strings MUST BE validated before being fed to the function.

2- The above function can only handle forward moving date ranges. If you want backward moving date ranges, simply reverse the date order in the function call and add a minus after $x=. (Pretty slick, eh?)

function getDatesFromRange($a,$b,$x=0,$dates=[]){
    while(end($dates)!=$b && $x=-array_push($dates,date("Y-m-d",strtotime("$a +$x day"))));
    return $dates;
}
var_export(getDatesFromRange('2010-10-05','2010-10-01'));

One more extension/consideration...

Imagine you have a multi-cultural (or sloppy) user base, and your function MUST be able to receive start and end dates in different valid formats AND you need to be able to output the array in any of the valid formats? By minor adjustment, I've provided a solution for that.

By "valid" I mean YYYY-MM-DD, MM/DD/YYY, and DD-MM-YYYY, these are massively popular standards world-wide, if another format is necessary then usability would come down to strtotime's comprehension of it.

Here is the Demo.

Code:

function getDatesFromRange($a,$b,$format='Y-m-d',$dates=[],$x=0){
    while(date($format,strtotime(end($dates)))!=date($format,strtotime($b)) && $x=array_push($dates,date($format,strtotime("$a +$x day"))));
    return $dates;
}

$formats=array("Computer"=>'Y-m-d',"American"=>'m/d/Y','Non-American'=>'d-m-Y');
$start='15-02-2017';    // Non-American formatted start date
$end='2017-02-27';  // Computer formatted start date
foreach($formats as $label=>$format){
    echo "<br>$label<br>";
    var_export(getDatesFromRange($start,$end,$format));
    echo "<br>";
}

Output

Computer
array ( 0 => '2017-02-15', 1 => '2017-02-16', 2 => '2017-02-17', 3 => '2017-02-18',
        4 => '2017-02-19', 5 => '2017-02-20', 6 => '2017-02-21', 7 => '2017-02-22',
        8 => '2017-02-23', 9 => '2017-02-24', 10 => '2017-02-25', 11 => '2017-02-26',
        12 => '2017-02-27', )

American
array ( 0 => '02/15/2017', 1 => '02/16/2017', 2 => '02/17/2017', 3 => '02/18/2017',
        4 => '02/19/2017', 5 => '02/20/2017', 6 => '02/21/2017', 7 => '02/22/2017',
        8 => '02/23/2017', 9 => '02/24/2017', 10 => '02/25/2017', 11 => '02/26/2017',
        12 => '02/27/2017', )

Non-American
array ( 0 => '15-02-2017', 1 => '16-02-2017', 2 => '17-02-2017', 3 => '18-02-2017',
        4 => '19-02-2017', 5 => '20-02-2017', 6 => '21-02-2017', 7 => '22-02-2017',
        8 => '23-02-2017', 9 => '24-02-2017', 10 => '25-02-2017', 11 => '26-02-2017',
        12 => '27-02-2017', )

Now some people don't 100% trust strtotime() because of some buggy behaviors. I think I've read that it will foul up when trying to jump a month from a leap-day. However, unless someone can reproduce it to prove me wrong, strtotime() is never going to let you down when you are only incrementing by one day.

查看更多
登录 后发表回答