[英]Add the correct number of days for each month
Using the following function I can display the years and months between two dates, but how can I add the correct days for each month as another array within each month? 使用以下功能,我可以显示两个日期之间的年和月,但是如何将每个月的正确日期添加为每个月内的另一个数组? I can't just add the days manually as I need it to account for leap years etc. 我不能只是手动添加日期,因为我需要它来说明leap年等。
function yearMonth($start_date, $end_date)
{
$begin = new DateTime( $start_date );
$end = new DateTime( $end_date);
$interval = new DateInterval('P1M'); // 1 month interval
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt )
$years[$dt->format( "Y" )][] = $dt->format( "F" );
return $years;
}
$list = yearMonth("2007-03-24", "2009-06-26");
var_dump($list);
Since nobody else answered: 由于没有人回答:
function yearMonth($start_date, $end_date)
{
$begin = new DateTime( $start_date );
$end = new DateTime( $end_date);
$interval = new DateInterval('P1D'); // 1 month interval
$period = new DatePeriod($begin, $interval, $end);
$lastMonth = null;
$lastYear = null;
$aResult = array();
foreach ( $period as $dt )
{
if ($dt->format('Y') != $lastYear)
{
$lastYear = $dt->format('Y');
}
if ($dt->format('F') != $lastMonth)
{
$lastMonth = $dt->format('F');
}
if (!isset($aResult[$lastYear]))
{
$aResult[$lastYear] = array();
}
if (!isset($aResult[$lastYear][$lastMonth]))
{
$aResult[$lastYear][$lastMonth] = array();
}
$aResult[$lastYear][$lastMonth][] = $dt->format('d');
}
return $aResult;
}
On a side note I am planing to create a sort of Gantt chart style flat layout in table format of the years, months and days between dates. 附带说明一下,我计划以日期之间的年,月和日为表格格式,创建一种甘特图样式的平面布局。 Do you think this is a suitable way of generating that? 您是否认为这是产生这种情况的合适方式? Or is there a better way? 或者,还有更好的方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.