PHP strtotime() 没有返回正确的月份

标签 php

由于当前月份/年份是 2012 年 1 月,为什么以下代码返回 2011 年 12 月而不是 2011 年 11 月?

echo date("F Y", strtotime("-2 months"));

如果它有所不同,这是在 PHP 5.3.0 上。

最佳答案

要得到你正在寻找的东西,你可以使用这个相当冗长的版本:

echo date("F Y", strtotime("first day of this month - 2 months"));

此处详细描述了原始版本的问题:http://derickrethans.nl/obtaining-the-next-month-in-php.html .引用如下:

Over and over again PHP users complain that next month in PHP's date-string parser doesn't go to the next month, but instead skips to the one after next month; like in the following example:

<?php
$d = new DateTime( '2010-01-31' );
$d->modify( 'next month' );
echo $d->format( 'F' ), "\n";
?>

The output of the little script will be March. March obviously doesn't follow January as February is in between. However, the current behavior is correct. The following happens internally:

next month increases the month number (originally 1) by one. This makes the date 2010-02-31. The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd. The formatting strips off the year and day, resulting in the output March. This can easily be seen when echoing the date with a full date format, which will output March 3rd, 2010:

这里是加月,减月也是一样;没有 11 月 31 日,因此 strtotime 方法将其“更正”为 12 月 1 日。

关于PHP strtotime() 没有返回正确的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9087462/

相关文章:

php - PayPal IPN 已验证握手但 IPN 无效

php - Javascript 无法获取 AJAX MODAL 形式的变量值

php - 如何在 JS 脚本中正确回显 PHP 变量?

javascript - 在 Laravel 中基于选项标签渲染表格

php - 为什么我的 PHP 联系表单发送的电子邮件不是 HTML 格式?

php - 如何在 php 中检索距 GMT+0 的时区偏移量?

php - 如何在 PHP 中对 JSON 数据进行分页?

php - 如何使用外部 PHP 脚本获取当前 Joomla 用户

java - 密码错误解密java

javascript - 将我的数据库中可用的 pdf 上传到我的服务器