I see there is strange problem in php with month addition and subtraction.
My questions are:
A few examples:
echo date('Y-m-d',strtotime('2011-03-31 -1 months')); //2011-03-03
echo date('Y-m-d',strtotime('2011-03-30 -1 months')); //2011-03-02
echo date('Y-m-d',strtotime('2011-03-29 -1 months')); //2011-03-01
echo date('Y-m-d',strtotime('2011-03-28 -1 months')); //2011-02-28
The cal_days_in_month() function returns the number of days in a month for a specified year and calendar.
To get the last day of a month, you can use the php date() function and format with “Y-m-t”. “t” returns the last day of a month.
php $dt = "2008-02-23"; echo 'First day : '. date("Y-m-01", strtotime($dt)).
From your examples, it looks like it's subtracting 1 from the month part, and then correcting for illegal dates. Your second example:
2011-03-30 - 1 month = 2011-02-30
. This date does not exist, as February 2011 had only 28 days. 30 - 28 = 2
, so it puts it as the 2nd day of the following month.
However, I have not found documentation about this.
Either way, assuming I'm right, the answer to your question is no, "1 month" does not have a (constant) equivalent in days, it depends on the input.
The way strtotime
parses date information is going to be very valuable here.
What you seem to want is the first day of the previous month, right?
Well, you can chain together many of these relative commands. For example, from the PHP interactive shell:
php > $d = date_create('2011-03-28 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
2011-02-01 00:00:00
php > $d = date_create('2011-03-29 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
2011-02-01 00:00:00
php > $d = date_create('2011-03-30 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
2011-02-01 00:00:00
php > $d = date_create('2011-03-31 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
2011-02-01 00:00:00
php > $d = date_create('2011-04-01 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
2011-03-01 00:00:00
first day
asks for the first day of the current month. Asking for -1 month
goes to the previous month, on the same day. Because we've already rewound to the first day of the month, this will always work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With