gpt4 book ai didi

PHP date() 和 strtotime() 在 31 日返回错误的月份

转载 作者:IT王子 更新时间:2023-10-29 00:07:41 25 4
gpt4 key购买 nike

我正在使用 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 日时运行,则下个月(即 2 月)将显示为 3 月。即上面的脚本应该返回

01/2012
02/2012
03/2012

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

01/2012
03/2012
03/2012

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

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

最佳答案

如文档中所述,您应该将当月第一天的日期作为第二个参数传递给 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

关于PHP date() 和 strtotime() 在 31 日返回错误的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9058523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com