开发者

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

I'm trying to get the number of month开发者_如何学C before of the current month (now is 04 (april), so I'm trying to get 03). I'm trying this:

date('m')-1;

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


The correct way to do this really is:

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

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


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.

Instead, use the following:

date('n') - 1;


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

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


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.


intval(date('m'))

for the current month

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

for the previous month, also for december/january


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

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


This works too.

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


This should do it for you...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜