【问题标题】:PHP strtotime bug help fixPHP strtotime bug 帮助修复
【发布时间】:2014-04-30 04:29:10
【问题描述】:
 $end = strtotime('2011-09-01');
 $start = strtotime('today');

 while($start > $end)
 {
echo date('F Y', $start) . "<br>";

$start = strtotime("-1 month", $start);
 }

结果: 2014 年 4 月 2014 年 3 月 2014 年 3 月 2014 年 2 月 2014年一月 2013年12月 ...等

为什么我两次收到 2014 年 3 月? 如果有人可以帮忙,谢谢。

【问题讨论】:

  • 因为今年没有 2 月 29 日.... 4 月 29 日(今天)-1 月 = 3 月 29 日,3 月 29 日 -1 月 = 2 月 29 日,即2 月的最后一天,所以你会得到 3 月 1 日、3 月 1 日 -1 个月 = 2 月 1 日,等等......如果你在呼应日期以及月份和年份,你会自己看到这一点

标签: php strtotime


【解决方案1】:

我能够让它与DateTime() 一起工作。从结束日期开始,我从本月的第一天开始。这使得每个月的天数变得无关紧要。然后我所要做的就是反转日期数组以使其符合您想要的格式。

$start    = new DateTime('2011-09-01');
$end      = new DateTime();
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);

$months= array();
foreach ($period as $dt) { 
    $months[] = $dt->format('F Y');
}
$months = array_reverse($months);
echo implode('<br>', $months);

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多