Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtotime and DateTime giving wrong year when parsing a year

Tags:

php

strtotime

$year = date('Y', strtotime("2012"));
var_dump($year);//returns 2013

This is happening with an old server with php 5.2 and a new one with php 5.4

The server uses strtotime to get the year from a string like 2012-01-01 or 2012-01 or 2012

I also tried it using $dt = new DateTime('2012') and then getTimestamp returns "1374516720" which is "Mon, 22 Jul 2013 18:12:00 GMT"

What is causing this bug? In the documentation it says that strtotime accepts only the year

I don't know what to do...

Edit:

$year = date('Y', strtotime("2012"));

gets treated as military time, 20:12 current year

like image 695
Timo Huovinen Avatar asked Dec 25 '22 23:12

Timo Huovinen


2 Answers

Using a complete date string YYYY-MM-DD and the 01.01 as the day did the trick for me:

$year = date('Y', strtotime("2012-01-01"));
var_dump($year);//returns 2012

Normally I would suggest to use DateTime::createFromFormat() as @Rufinus suggested, but the method is not available in PHP5.2 (what you are using on one of the servers). Maybe a reason fro upgrading the old one? ;)


Reasons why this happens:

While the manual says at one point that YYYY (and just YYYY) formats are ok, it tells about restrictions to that behaviour some lines below: strtotime() called with YYYY will under special circumstances return a time stamp for today, 20:12:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

I don't know what they mean when saying a time string has already been found. But you can see this behaviour using the following line:

var_dump(date("Y-m-d H:i:s", strtotime('2012')));
// output: string(19) "2013-07-22 20:12:00"

This leads to the result 2013.

like image 187
hek2mgl Avatar answered Jan 14 '23 06:01

hek2mgl


EDIT: different formats...

try

$date = '2012-11';

$parts = explode('-', $date);
switch(count($parts)){
        case 2:
                $format = 'Y-m';
                break;
        case 3:
                $format = 'Y-m-d';
                break;
        case 1:
        default:
                $format = 'Y';
                break;
}

$date = DateTime::CreateFromFormat($format, $year);
echo $date->format('Y');
like image 32
Rufinus Avatar answered Jan 14 '23 07:01

Rufinus