为什么PHP date('m',strtotime('-1 months'))今天不能正常工作? 07/31 [英] Why does PHP date('m', strtotime('-1 months')) not work correctly for today? 07/31

查看:212
本文介绍了为什么PHP date('m',strtotime('-1 months'))今天不能正常工作? 07/31的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本可以像这样获取PHP的当前和上个月:

I have a script that gets the current and last month in PHP like so:

$currentMonth = date('m');
//Expected:07
//Result:07
$lastMonth = date('m', strtotime('-1 months'));
//Expected:06
//Result:07

今天碰巧是7月31日或月底。

Today happens to be the 31 or end of the month of July. Is this result to be expected from PHP?

使用-31天时,结果是否符合预期?

When using -31 days the result is as expected:

$lastMonth = date('m', strtotime('-31 days'));
//Expected:06
//Result:06


推荐答案

这是一个不会过期的更干净的测试用例

<?php
$origin = mktime(18, 0, 0, 7, 31, 2015);
var_dump( date('r', $origin), date('r', strtotime('-1 months', $origin)) );





string(31) "Fri, 31 Jul 2015 18:00:00 +0200" 
string(31) "Wed, 01 Jul 2015 18:00:00 +0200"

我很确定这是一个文档问题,因为该手册明确指出了这一点(强调我的意思):

I'm pretty sure it's a documentation issue, because the manual clearly states this (emphasis mine):


相对月份值是根据通过的月份的长度来计算的。例如 +2 month 2011-11-30,
会产生 2012-01-30。这是因为11月的长度为30
天,而12月的长度为31天,总共产生了61天。

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

...这是错误的。

PHP错误跟踪器具有吨骗子。他们都以不是错误的身份被关闭。以下是相关的 2009年的评论,它对此进行了解释:

PHP bug tracker has tons of dupes about this. They're all closed as not a bug. Here's a relevant comment from 2009 that explains it:


我同意这是一个令人讨厌的行为。

I agree that this is an annoying behaviour.

另外,实现也有问题。基本上如果您使用'+1
month',它将使用月份数字,加1并将结果解析为新的
日期

Also, the implementation is problematic. Basically if you use '+1 month' it takes the month number, adds 1 and parses result as a new date.

如果您在每月的第一天使用 +1个月,则会将日期设置为该月的下一个月的

If you use '+1 month' on the first of the month, it sets the date to the next first of the month.

此行为给人的印象是php考虑
a一个月的长度,这是不正确的。

This behaviour gives the impression, that php considers the length of a month, which is not true.

但是如果您使用'+1 month '在一个月的最后一天,结果是
意外
,因为2009-05-31变为2009-06-31,这是一个无效的日期
,然后解释为2009-07- 01。

But if you use '+1 month' on the last day of a month, the result is unexpected as 2009-05-31 becomes 2009-06-31 which is an invalid date and then interpreted as 2009-07-01.

至少应在文档中提及

这篇关于为什么PHP date('m',strtotime('-1 months'))今天不能正常工作? 07/31的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆