Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

date - PHP DateTime::createFromFormat behavoiur

Today I've encountered something confusing for me with the behaviour of the DateTime::createFromFormat function.

In my case I have a string, representing the date in the following format m/Y (05/2017). When I want to convert the string to DateTime object I've encountered the following issue:

$date = DateTime::createFromFormat('m/Y', '02/2017');

When I dump the $date variable, the date property inside is '2017-03-03 11:06:36.000000'

But if I add the date before the month $date = DateTime::createFromFormat('d/m/Y', '01/02/2017'); I get back an object with correct date property. (unfortunately I cant change the format of the date and add the day. It must be m/Y).

The fix I've come up with is to concatenate the first day of the month to the date string I have $date = '01/'.$dateString; but I rather not to do that because it's hardcoded.

What is wrong here? Does the createFromFormat function lack information of how to create the object? I'm quite confused with this. Thanks for everyone's help in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By default, PHP will populate missing date values with those of the current date/time; so

$date = DateTime::createFromFormat('m/Y', '02/2017');

will populate the missing day value with the current date; and as 31st February is an invalid date, it will roll forward into March. Likewise, hours/minutes/seconds will be populated with the missing time values based on the current time.

If you want to force the behaviour of forcing to the beginning of the month/time, then modify your mask with a leading !

$date = DateTime::createFromFormat('!m/Y', '02/2017');

This will populate the missing day with the 1st of the month, and the time with 00:00:00

Alternatively, a trailing | will have the same effect

$date = DateTime::createFromFormat('m/Y|', '02/2017');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...