如何在PHP中设置日期限制?

时间:2011-07-29 05:50:45

标签: php date

如何限制此日期或将此日期从star_date打印到end_date? 离。

$start_date="2011-05-15";//june 15 2011

$end_date="2011-07-30";//july -7,2011

The result should be.

$dates[]="2011-05-15";
$dates[]="2011-05-16";
$dates[]="2011-05-17";
$dates[]="2011-05-18";
$dates[]="....";
$dates[]="....";
$dates[]="....";
$dates[]="....";
until it reaches.
$dates[]="2011-07-30";

6 个答案:

答案 0 :(得分:3)

我建议将开始日期作为对象,并继续在循环中添加1天(http://www.php.net/manual/en/datetime.add.php),直到到达结束日期。< / p>

<?php
$start_date = new DateTime('2011-05-15');
$end_date = new DateTime('2011-07-30');
while($end_date > $start_date)
{
   echo $start_date->format('Y-m-d') . "\n";
   $start_date->add(new DateInterval('P1D'));
}
?>

上述代码尚未经过测试。

答案 1 :(得分:2)

这可以做到......

$start_date = strtotime('2011-05-15'); //june 15 2011
$end_date = strtotime('2011-07-30'); //july -7,2011
$dates = array();
for ($i=$start_date; $i<=$end_date; $i+=86400) {
    $dates[] = date('Y-m-d',$i);
}

答案 2 :(得分:2)

$start_date="2011-05-15";
$end_date="2011-07-30";
$date=$start_date;
while (strtotime($new_date) != strtotime($end_date))
{
   echo $new_date=date("Y-m-d",strtotime("+1 day", strtotime($date)))."<br>";
   $dates[]=$new_date;
   $date=$new_date;       
}

答案 3 :(得分:2)

另一个......

date_default_timezone_set('America/Los_Angeles');

$startDate='2011-05-15';
$endDate='2011-07-30';

$t1=strtotime($startDate);
$days=(strtotime($endDate)-$t1)/86400;

for($i=0;$i<=$days;$i++) $dates[]=date('Y-m-d',$t1+($i*86400));

print_r($dates);

对于'效率不高但在大多数情况下会在线上工作':

for($t=strtotime($startDate);$t<=strtotime($endDate);$t+=86400) $dates[]=date('Y-m-d',$t);

对于那些知道的人来说,这是今天早上练习的最后一次:

$dates=array_map(create_function('$t','return date("Y-m-d",$t);'),range(strtotime($startDate),strtotime($endDate),86400));

答案 4 :(得分:1)

这有效:

$start_date = "2011-05-15";
$end_date = "2011-07-07";

$dates = array();
$stop = strtotime($end_date);
for($i = strtotime($start_date); $i <= $stop; $i += 86400)
    $dates[] = date('Y-m-d', $i);

PS。我将您的7月日期更改为07-07以符合您的评论。

答案 5 :(得分:0)

$start_date = strtotime('2011-05-15');
$end_date = strtotime('2011-07-30');
$dates = array();
for ($i = $start_date; $i<=$end_date; $i+= (strtotime('+1 day') - strtotime('now'))) {
   $dates[] = date('Y-m-d',$i);
}