简体   繁体   中英

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM