Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime class and last month

Tags:

php

datetime

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.

like image 372
egis Avatar asked May 31 '12 11:05

egis


People also ask

How do I find out the last date of the month?

We will use date() and strtotime() function to get the last day of the month.

How can I get last date of previous month in PHP?

$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")); <?

How do you get the first day of the month in PHP?

$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.


2 Answers

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.

like image 96
dan-lee Avatar answered Sep 30 '22 13:09

dan-lee


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";
?>
like image 20
ClydeFrog Avatar answered Sep 30 '22 13:09

ClydeFrog