datetime — PHP: вернуть все даты между двумя датами в массиве

Ожидаемый вклад:

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

Ожидаемый результат:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

191

Решение

Вы также можете взглянуть на DatePeriod учебный класс:

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

Который должен получить массив с объектами DateTime.

Итерировать

foreach ($period as $key => $value) {
//$value->format('Y-m-d')
}
346

Другие решения

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=array();

$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;
}

источник: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

146

Это очень, очень гибкий.

/**
* 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;
}
123

Обратите внимание, что ответ, предоставленный ViNce, НЕ включает Дата окончания за период.

Если вы используете PHP 5.3+, лучше всего использовать такую ​​функцию:

/**
* 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;
}

Затем вы должны вызвать функцию, как ожидалось:

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

Запустить демо

Примечание о DatePeriod учебный класс: Вы можете использовать 4-й параметр DatePeriod, чтобы исключить дату начала (DatePeriod::EXCLUDE_START_DATE), но вы не можете в настоящее время указать дату окончания.

32

Просто, но как шарм:

    $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();
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;
}

использовать как

GetDays('2007-01-01', '2007-01-31');
12

Это коротко, мило и должно работать в PHP4 +.

function getDatesFromRange($start, $end){
$dates = array($start);
while(end($dates) < $end){
$dates[] = date('Y-m-d', strtotime(end($dates).' +1 day'));
}
return $dates;
}
12

Есть много способов сделать это, но, наконец, все зависит от используемой вами версии PHP. Вот краткое изложение всех решений:

получить версию PHP:

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

вы должны обновить 🙂

8
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector