我有两个日期 - 开始日期和结束日期。我需要返回月份的数组(“YM”格式),其中包括起始和结束日期之间的每个月,还有几个月,这些日期是在我已经试过:返回包含开始日期和结束日期的月数
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-15');
$month = $start;
while($month <= $end) {
$months[] = date('Y-m', $month);
$month = strtotime("+1 month", $month);
}
的问题是在上面的例子中,它只将“2010-08”添加到数组中,而不是“2010-09”。我觉得解决方案应该是显而易见的,但我看不到它。
请注意,这应该考虑到像帐户情况:
$start = strtotime('2010-08-20');
$end = strtotime('2010-08-21');
// should return '2010-08'
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-01');
// should return '2010-08,2010-09'
$start = strtotime('2010-08-20');
$end = strtotime('2010-10-21');
// should return '2010-08,2010-09,2010-10'
此外,PHP的我的主机上的版本是5.2.6,因此具有这些范围内的工作。
我使用的解决方案是基于以下答案。设置$start
到月份的第一天。然而,我不能仅仅使用strtotime()
,而是必须使用我在网上找到的另一个功能。
function firstDayOfMonth($uts=null)
{
$today = is_null($uts) ? getDate() : getDate($uts);
$first_day = getdate(mktime(0,0,0,$today['mon'],1,$today['year']));
return $first_day[0];
}
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-15');
$month = firstDayOfMonth($start);
while($month <= $end) {
$months[] = date('Y-m', $month);
$month = strtotime("+1 month", $month);
}
我真的很想喜欢你的解决方案,因为它的清洁/逻辑,当我使用'的strtotime(“这个月的第一天”,$月份)在我的Mac测试'它工作正常,返回'$ month'中定义的月份的第一天。但是当我在主机上完成同样的事情时,它会返回1970-01-01。 – ggutenberg 2010-08-21 06:20:09
这让我走上了正轨。在问题中提供了完整的解决方案。 – ggutenberg 2010-08-21 10:11:27