Return all dates between two dates in an array in PHP
Given two dates (start date and end date) and the task is to return all the dates in an array.
Example 1: In this example, use date interval class which stores fixed amount of time (in years, months, days, hours etc) or relative time string in the format that DateTime.
<?php
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 ;
}
$Date = getDatesFromRange( '2010-10-01' , '2010-10-05' );
var_dump( $Date );
?>
|
Output:
array(5) {
[0]=>
string(10) "2010-10-01"
[1]=>
string(10) "2010-10-02"
[2]=>
string(10) "2010-10-03"
[3]=>
string(10) "2010-10-04"
[4]=>
string(10) "2010-10-05"
}
Example 2: This example use strtotime() function which is used to convert an English textual date-time description to a UNIX timestamp. It returns a timestamp on success, False otherwise.
<?php
$Date1 = '01-10-2010' ;
$Date2 = '05-10-2010' ;
$array = array ();
$Variable1 = strtotime ( $Date1 );
$Variable2 = strtotime ( $Date2 );
for ( $currentDate = $Variable1 ; $currentDate <= $Variable2 ;
$currentDate += (86400)) {
$Store = date ( 'Y-m-d' , $currentDate );
$array [] = $Store ;
}
print_r( $array );
?>
|
Output:
Array
(
[0] => 2010-10-01
[1] => 2010-10-02
[2] => 2010-10-03
[3] => 2010-10-04
[4] => 2010-10-05
)
Last Updated :
21 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...