【问题标题】:PHP: Can't get month at the right yearPHP:无法在正确的年份获得月份
【发布时间】:2016-03-21 03:26:20
【问题描述】:

对于下面的代码,我希望拥有当前月份和接下来的 12 个月。我为它使用了一个循环,除了“一月”之外,一切都很好。而且我只是不知道出了什么问题。

for ($i = 0; $i <= 12; $i++) {
    $months[ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")))] = ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
    echo ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
}

回声输出:

December 2015 Januari 2015 Februari 2016 Maart 2016 April 2016 Mei 2016 Juni 2016 Juli 2016 Augustus 2016 September 2016 Oktober 2016 November 2016 December 2016

【问题讨论】:

  • 尝试使用date('M-y') 而不是('Y-m')
  • 提示:在进行任何类型的计算(包括时间)时不要滥用字符串。
  • @Fredrik 谢谢,它已经奏效了。但是为什么我的错了?

标签: php forms date select cakephp-2.x


【解决方案1】:

这样的事情呢?

<?php

$start = new DateTimeImmutable('first day of this month');
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, 12);

foreach ($period as $date) {
    echo $date->format('F Y') . PHP_EOL;
}

【讨论】:

    【解决方案2】:

    你可以简单地使用:

    $date = new DateTime('first day of this month');
    
    for ($i = 0; $i < 13; $i++) {
        echo $date->format('F Y,');
        $date->modify('+1 month');
    }
    

    输出将是:

    2015 年 12 月、2016 年 1 月、2016 年 2 月、2016 年 3 月、2016 年 4 月、2016 年 5 月、2016 年 6 月、2016 年 7 月、2016 年 8 月、2016 年 9 月、2016 年 10 月、2016 年 11 月、2016 年 12 月,

    【讨论】:

    • 我很抱歉,但需要它在荷兰语和选择的 var 中(以表格形式)。 Frederik 的解决方案运行良好。
    • 如果当前日期接近月底,您可能会遇到跳过月份的问题。例如,设置$date = new DateTime('2015-12-31')' 将跳过二月。您需要确保是月初。
    • 我刚刚验证过,你是对的。我刚刚更新了我的答案。谢谢。你的回答也很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多