Rejoanul Alam
Rejoanul Alam

Reputation: 5398

strtotime() with only year return wrong data

Following returning correct date

echo date('Y-m',strtotime('2009-3'));

But this returning wrong data when just year

echo date('Y',strtotime('2009'));

This showing current year. Whats wrong there

Upvotes: 0

Views: 2313

Answers (1)

Rizier123
Rizier123

Reputation: 59701

Because only out of "2009" strtotime() can't create a valid Unix timestamp. So you need to pass a full date like this:

echo date('Y',strtotime('2009-04-07'));
                       //^^^^^^^^^^

Also a quote from the manual shows this too:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp

EDIT:

If you only have the year you can use DateTime::createFromFormat, like this:

$date = DateTime::createFromFormat("Y", "2009");
echo $date->format("Y");

output:

2009

Upvotes: 2

Related Questions