返回包含开始日期和结束日期的月数
我有两个日期 - 开始日期和结束日期。我需要返回月份的数组(“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);
}
的问题是,$开始一天比结束日大,所以你加入个月后开始其比结束大,解决方案是使用该月的第一天,像这样2010-08-01后你加1个月,你会得到至少等于$ end;)
这应该做你所需要的。
$start = strtotime('2010-08-20');
$end = strtotime('2010-10-15');
$month = $start;
$months[] = date('Y-m', $start);
while($month <= $end) {
$month = strtotime("+1 month", $month);
$months[] = date('Y-m', $month);
}
这几乎可以工作,但当$ start和$ end在同一个月时,它会崩溃。 – ggutenberg 2010-08-21 06:33:03
它会以任何一种方式返回开始月份,只要$ start和$ end在同一个月内不会进入while,则数组月份只会包含$ start。试试print_r($ months);过了一段时间,你会看到。 – Centurion 2010-08-21 07:32:54
使用'$ start = strtotime('2010-08-20')在PHP 5.3.1上进行本地测试; $ end = strtotime('2010-08-21');'在这种情况下,它仍然进入循环,增加'$ month'并且写入第二个月到数组。 – ggutenberg 2010-08-21 07:52:24
环路下面添加
if(date('d',$month) != date('d',$end))
$months[] = date('Y-m', $month);
。这意味着,如果仅在$end
(日期不同:最后差异小于一个月)中添加了最后一个月份。
RBO
当$ start和$ end在同一个月份时,这也会失败。 – ggutenberg 2010-08-21 06:36:06
我真的很想喜欢你的解决方案,因为它的清洁/逻辑,当我使用'的strtotime(“这个月的第一天”,$月份)在我的Mac测试'它工作正常,返回'$ month'中定义的月份的第一天。但是当我在主机上完成同样的事情时,它会返回1970-01-01。 – ggutenberg 2010-08-21 06:20:09
这让我走上了正轨。在问题中提供了完整的解决方案。 – ggutenberg 2010-08-21 10:11:27