strtotime()只有年份返回错误的数据

strtotime()只有年份返回错误的数据

问题描述:

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

返回正确的日期 p>

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

但是这年只返回错误的数据 p>

  echo date('Y',strtotime('2009')); 
  code>  pre> 
 
 

显示当前年份。 那里错了 p> div>

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