Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong month (February) - DateTime::createFromFormat [duplicate]

Tags:

php

The date conversion from string returns wrong values for the 2nd month (February):

$dtformat = 'Y-m-01';
$curDate = DateTime::createFromFormat('Y-m', '1996-02');
print_r($curDate);
$dt     = $curDate->format($dtformat);
echo $dt."\n";

Instead of "1996-02-01", it returns "1996-03-01". This is the $currDate array:

DateTime Object ( 
    [date] => 1996-03-02 01:19:01 
    [timezone_type] => 3 
    [timezone] => America/New_York 
)

All other months work fine. What am I missing here?

Thanks!

like image 297
user2723490 Avatar asked Jan 31 '14 06:01

user2723490


2 Answers

It's not a bug according to this post.

Cause: When we don't provide date to createFromFormat it will take as today's date by default. So in this case it will be 1996-02-31 which does not exist & thus it will take a next month.

Solution: Need to provide day to avoid such scenario.

$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
like image 110
Rikesh Avatar answered Oct 21 '22 07:10

Rikesh


Try with this code:

$curDate = DateTime::createFromFormat('!Y-m', '1996-02');

The manual explains:

!
Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch

like image 5
Jenz Avatar answered Oct 21 '22 07:10

Jenz