user5392189
user5392189

Reputation: 13

DateTime returns wrong year

My code is like following:

<?php
$newDate = new DateTime('2012');
echo $newDate->format('Y');

Why $newDate->format('Y') returns 2015 (current year) and not 2012?

Upvotes: 0

Views: 463

Answers (1)

php_nub_qq
php_nub_qq

Reputation: 16017

Because 2012 is not a valid date string. By default the date and time set into the object will be the current, which is 2015. You can hint what format you are going to use with DateTime::createFromFormat

$date = DateTime::createFromFormat('Y', '2012');
echo $date->format('Y');

Upvotes: 1

Related Questions