【问题标题】:PHP date() and strtotime() return wrong months on 31stPHP date() 和 strtotime() 在 31 日返回错误月份
【发布时间】:2012-02-21 22:21:15
【问题描述】:

我正在使用 date()strtotime() 函数在下拉列表中显示接下来的 3 个月。

PHP 代码:

   echo date("m/Y",strtotime("+0 months")); 
   echo date("m/Y",strtotime("+1 months"));
   echo date("m/Y",strtotime("+2 months")); 

但是,如果脚本在服务器日期为 30 日或 31 日时运行,则下个月(二月)将改为三月。 即上面的脚本应该返回

01/2012
02/2012
03/2012

但是,它实际上显示的不是那个

01/2012
03/2012
03/2012

这是因为二月没有 30 日或 31 日,所以脚本将“31/02”翻译成“01/03”。

我已经阅读了 php.net 上的strtotime() 页面,这个问题已经提出,但没有任何有用的解决方案。那么任何人都可以帮我找到解决这个问题的简单方法吗?提前致谢!

【问题讨论】:

标签: php date strtotime


【解决方案1】:

不要使用 strtotime() 按月获取偏移日期。它只能在 PHP 5.3+ 中正常工作。 解决此类问题的最佳方法是使用mktime()。 下面是一个示例代码:

function getOffsetByMonths($nMonths, $nNow = 0) {
    if ($nNow)
        return mktime(0, 0, 0, date('n', $nNow)+ $nMonths, 1, date('Y', $nNow));
    else
        return mktime(0, 0, 0, date('n')+ $nMonths);
}
$nNow = mktime(0, 0, 0, 1, 31, 2013);
echo "Now: ". date("Y-m-d", $nNow).
"<br>(Now - 1 month): ". date("Y-m", getOffsetByMonths(-1, $nNow)). "-xx".
"<br>(Now - 2 month): ". date("Y-m", getOffsetByMonths(-2, $nNow)). "-xx".
"<br>(Now - 3 month): ". date("Y-m", getOffsetByMonths(-3, $nNow)). "-xx";

【讨论】:

    【解决方案2】:

    尝试在您的 strtotime 中使用“first day of”,如下所示:

    strtotime("first day of +1 month");
    

    这将通过将日期(如果今天是 1 月 30 日)转换为 02-01(2 月 1 日)来修复日期(如果今天是 1 月 30 日),例如 02-30(产量 3 月 2 日),然后会为您提供正确的月份。它比其他方法更简洁,更容易记住。

    【讨论】:

    • 非常优雅的解决方案。
    • 不适用于 31 日的FIRST DAY OF -2 MONTHSbase 很重要
    • Shrugg - 今天 2018 年 5 月 31 日,echo date('Y-m-d', strtotime('FIRST DAY OF -2 MONTH')); 收益 -> 2018-03-01。 5-2 = 3。似乎有效,你有什么例子没有?
    【解决方案3】:

    如文档中所述,您应该将当月第一天的日期作为第二个参数传递给strtotime() 函数:

    $base = strtotime(date('Y-m',time()) . '-01 00:00:01');
    echo date('m/Y',strtotime('+0 month', $base));
    echo date('m/Y',strtotime('+1 month', $base));
    echo date('m/Y',strtotime('+2 month', $base));
    

    看看它是否有效:http://ideone.com/eXis9

    01/2012

    02/2012

    03/2012

    【讨论】:

    • 考虑到$base = strtotime('2016-12-31' . '-01 00:00:01');+2 month+3 month 的解决方案基台在 2 月打印 2 次​​span>
    【解决方案4】:
    echo date('m/Y', strtotime(date('Y-m') . '-01 +2 months'));
    

    只需将其硬编码为当月的第一天。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2017-03-13
      相关资源
      最近更新 更多