简体   繁体   中英

PHP DateTime::createFromFormat return unexpected result

The code below keep returning 2018/03/02 instead of 2018/02/28 and I really don't know why.

var_dump(DateTime::createFromFormat('Y 年 m 月', "2018 年 02 月"));

Can you explains to me why it return result like that, and is there any work around for it.

Thank you

without explicitely providing the day portion will have the current day

Current day is 30 which takes by default if you not provide, which not present in February so it incremented by 2 days which tends to next month march.

If you want last date of current month put 01 as date and use like this

<?php
$date = DateTime::createFromFormat('Y 年 m 月 d', "2018 年 02 月 01");
var_dump($date->format("Y-m-t"));
?>

Demo

If you are getting value in variable then just add 01 string at last

$myDate = "2018 年 02 月";
$date = DateTime::createFromFormat('Y 年 m 月 d', $myDate." 01");

You have to specify a day :

var_dump(DateTime::createFromFormat('Y 年 m 月 d', "2018 年 02 月 01"));
// 2018-02-01

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