php 试图获取当月前一个月的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5733636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:20:27  来源:igfitidea点击:

Trying to get the number of the month before of the current month

phpdate

提问by ziiweb

I'm trying to get the number of month before of the current month (now is 04(april), so I'm trying to get 03). I'm trying this:

我试图获得当月之前的月份数(现在是04(四月),所以我试图获得03)。我正在尝试这个:

date('m')-1;

but I get 3. But what I want is to get 03.

但我明白了3。但我想要的是得到03.

回答by glebtv

The correct way to do this really is:

真正做到这一点的正确方法是:

date('m', strtotime('-1 month'));

date('m', strtotime('-1 month'));

As you will see strange things happen in January with other answers.

正如你会看到奇怪的事情发生在 1 月,还有其他答案。

回答by GordyB

The currently accepted response will result in an incorrect answer whenever the day of the month (for the current day) is a larger number than the last day of the month for the previous month.

只要当月中的某天(对于当天)大于上个月的最后一天,当前接受的响应将导致错误答案。

e.g. The result of executing date('m', strtotime('-1 month'));on March 29th (in a non-leap-year) will be 03, because 29 is larger than any day of the month for February, and thus strtotime('-1 month')will actually return March 1st.

例如,date('m', strtotime('-1 month'));在 3 月 29 日(非闰年)执行的结果将是 03,因为 29 比 2 月的任何一天都大,因此strtotime('-1 month')实际上将返回 3 月 1 日。

Instead, use the following:

相反,请使用以下内容:

date('n') - 1;

回答by Your Common Sense

You may be surprised, but date() function manual pagehas an exact example of what you need:

您可能会感到惊讶,但date() 函数手册页有一个您需要的确切示例:

$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));

回答by Luca C.

intval(date('m'))

for the current month

当月

(intval(date('m'))-1)%12

for the previous month, also for december/january

上个月,也是 12 月/1 月

回答by Ollie Brooke

date('m', strtotime('last month'));

This will work regardless of whether or not you're in January

无论您是否在一月份,这都将起作用

回答by jeroen

The result of your calculation is a number. If you want to format it like a string, you can use:

你的计算结果是一个数字。如果要将其格式化为字符串,可以使用:

$result = date('m')-1;
$string_result = sprintf("%02s", $result);

Edit:Note that this is only a partial solution to format a number like a string.

编辑:请注意,这只是将数字格式化为字符串的部分解决方案。

回答by cac

This works too.

这也有效。

printf("%02s", (date('m') - 1));

回答by Brandon McKinney

This should do it for you...

这应该为你做...

str_pad(date('m')-1,  2, '0', STR_PAD_LEFT);