包含两个不同日期之间日期的数组

时间:2012-07-12 12:11:54

标签: php

我目前正在制作一个日历脚本供我个人使用。因此,我需要你的帮助: - )

我有YYYY-MM-DD格式的两个日期。

例如:

2012-05-12 and
2012-05-16

我需要的是它们之间的日期:

2012-05-13
2012-05-14
2012-05-15

输出应该在一个数组中。我现在不管怎么开始......所以你有提示吗?

5 个答案:

答案 0 :(得分:5)

这是OOP方法,您应该使用它:

$a = new DateTime('2012-05-12');
$b = new DateTime('2012-05-16');

// to exclude the end date (so you just get dates between start and end date):
// $b->modify('-1 day');

$period = new DatePeriod($a, new DateInterval('P1D'), $b, DatePeriod::EXCLUDE_START_DATE);

foreach($period as $dt) {
  echo $dt->format('Y-m-d');
}

如需进一步阅读,请参阅DateTimeDateIntervalDatePeriod

答案 1 :(得分:3)

$date =  date("Y-m-d", strtotime("2012-05-12"));
$final_date = date("Y-m-d", strtotime("2012-05-16"));
while($date < $final_date){
   $date = date("Y-m-d", strtotime($date . " +1 day"));
   $dates[] = $date;
}

答案 2 :(得分:1)

function GetDays ($sStartDate, $sEndDate ) {  
  $sStartDate = gmdate( 'Y-m-d', strtotime( $sStartDate ) );  
  $sEndDate = gmdate( 'Y-m-d', strtotime( $sEndDate ) );  

  $aDays[] = $sStartDate;  

  $sCurrentDate = $sStartDate;  

  while( $sCurrentDate < $sEndDate ) {  
    $sCurrentDate = gmdate( 'Y-m-d', strtotime( '+1 day', strtotime( $sCurrentDate) ) );  

    $aDays[] = $sCurrentDate;  
  }  

  return $aDays;  
}  

print_r ( '2012-05-12', '2012-05-16' );

答案 3 :(得分:1)

function getDates($startTime, $endTime) {
    $day = 86400;
    $format = 'Y-m-d';
    $startTime = strtotime($startTime);
    $endTime = strtotime($endTime);
    //$numDays = round(($endTime - $startTime) / $day) + 1;
    $numDays = round(($endTime - $startTime) / $day); // remove increment 

    $days = array();

    for ($i = 1; $i < $numDays; $i++) { //change $i to 1
        $days[] = date($format, ($startTime + ($i * $day)));
    }

    return $days;
}

$days = getDates('2012-05-12', '2012-05-16');

输出:

Array
(
    [0] => 2012-05-13
    [1] => 2012-05-14
    [2] => 2012-05-15
)

正如Dan Lee所说,我将函数更改为仅获取日期间隔,不包括数组中的第一天和最后一天。

答案 4 :(得分:0)

以下是代码:

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

我参考了this网站。