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

4

3 回答 3

7

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.

于 2013-07-22T10:46:13.880 回答
3

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');
于 2013-07-22T10:44:22.147 回答
0

try more manual approach. i find strtotime not too reliable in edge cases and prefer to have more control over what is going on.

$parsed = explode('-',$input_string);
$year = (isset($parsed[0])) ? $parsed[0] : NULL;
$month = (isset($parsed[0])) ? $parsed[0] : 1;
$day = (isset($parsed[0])) ? $parsed[0] : 1;

$timestamp = mktime(0,0,0,$day,$month,$year);
echo date($your_preffered_format, $timestamp);
于 2013-07-22T10:58:59.233 回答