帮朋友处理一个数组时,用到了 PHP 中的 strtotime 函数,结果一不留神掉入陨石坑,久久不能自拔!
先说下 strtotime 的作用:
(PHP 4, PHP 5, PHP 7)
strtotime — 将任何字符串的日期时间描述解析为 Unix 时间戳
然后看下这个陨石坑:
echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) ); // PHP: 2009-03-03
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31
很明显,2月根本没有30号、31号,所以上面的 +1 month 直接跳到了三月!
那么,怎么避免这个问题呢?
echo date( "Y-m-d", strtotime( "first day of next month" ) ); // PHP: 2017-04-01
echo date( "Y-m-d", strtotime( "last day of next month" ) ); // PHP: 2009-04-30如果你无法肯定日期是否会出现异常,最好先处理好月份再去处理是哪一天!
本文通过一个具体例子揭示了PHP中strtotime函数处理日期时可能遇到的问题,特别是当涉及到月份加减操作时可能出现的日期异常情况,并提供了相应的解决方案。
510

被折叠的 条评论
为什么被折叠?



