This question already has an answer here:
这个问题在这里已有答案:
- PHP: Return all dates between two dates in an array 26 answers
PHP:返回数组中26个答案的两个日期之间的所有日期
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:
我有一个ajax数据对象,参与2013年11月12日的$ startDate和2014年1月31日的$ endDate,我想创建一个如下所示的数组:
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.
但脚本在30秒后超时。所以我想知道这样做的正确方法是什么。
2 个解决方案
#1
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);
?>
#2
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
#1
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);
?>
#2
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