PHP 中使用 strtotime "+1 month" 时发现的坑

strtotime - 将任何字符串的日期时间描述解析为 Unix 时间戳

然后看下这个陨石坑:

  1. echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) ); // PHP: 2009-03-03
  2. echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31

很明显, 2 月根本没有 30 号, 31 号, 所以上面的 +1 month 直接跳到了三月!

那么, 怎么避免这个问题呢?

  1. echo date( "Y-m-d", strtotime( "first day of next month" ) ); // PHP: 2017-04-01
  2. echo date( "Y-m-d", strtotime( "last day of next month" ) ); // PHP: 2009-04-30

如果你无法肯定日期是否会出现异常, 最好先处理好月份再去处理是哪一天!

来源: https://blog.csdn.net/lddtime/article/details/66480676

原文地址:https://www.cnblogs.com/rxbook/p/15328868.html