I have some weird behaviour with DateTime class.
Today is 2012-05-31. Timezone is "Europe/Vilnius".
Following code
$date = new DateTime('last month');
echo $date->format('Y-m-d');
outputs 2012-05-01
. Is this a php bug? By the way, $date = new DateTime('-1 month');
outputs the same.
We will use date() and strtotime() function to get the last day of the month.
$lastDay = date('t',strtotime('last month')); print_r($lastDay); Below, you'll find some examples of different ways to solve the How To Get Previous Month In Php problem. echo date('M Y', strtotime("-1 month")); //to get date with time of previous month echo date("Y-m-d H:i:s",strtotime("-1 month")); <?
$first_day = date('Y-m-01'); $last_day = date('Y-m-t'); Php Get First Day Of Month. There are a number of different approaches that can be taken to solve the same problem. The following paragraphs will examine the various alternative approaches.
This seems to be special case for months with 31 days:
Note that '-1 month' may produce unexpected result when used in last day of month that has 31 days (from http://www.php.net/manual/de/datetime.formats.relative.php#102947)
What you can do is:
$date = new DateTime('last day of last month'); // this is "2012-04-30" now
/// 'first day of last month' would work either, of course
And then it depends on what you are going to do with the date.
I think you need to have a datetime that already exist and modify it, like this:
<?php
$d = new DateTime( date("Y-m-d") );
$d->modify( 'last day of previous month' );
echo $d->format( 'Y-m-d' ), "\n";
?>
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