1

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

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

例如:

2012-05-12 and
2012-05-16

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

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

输出应该在一个数组中。我现在不知道如何开始......所以你有提示吗?

4

5 回答 5

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

于 2012-07-12T12:18:50.320 回答
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;
}
于 2012-07-12T12:15:41.883 回答
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' );
于 2012-07-12T12:17:19.920 回答
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 所说,我将函数更改为仅获取日期间隔,不包括数组中的第一天和最后一天。

于 2012-07-12T12:19:49.533 回答
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;
    }

我参考了这个网站。

于 2012-07-12T12:20:20.010 回答