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
744 views
in Technique[技术] by (71.8m points)

php - strtotime on incorrect dates

I found something odd about strtotime().

On dates that do not exist it returns the day after.

$d30= strtotime("2017-06-30");
Echo $d30 ."
";
Echo date("Y-m-d", $d30)."

";  // 2017-06-30

$d31= strtotime("2017-06-31");
Echo $d31 ."
";
Echo date("Y-m-d", $d31)."

";  // 2017-07-01

$d32= strtotime("2017-06-32");
Echo $d32 ."
";
Echo date("Y-m-d", $d32);         // 1970-01-01

https://3v4l.org/AjMAE

I understand the last one. It returns nothing as it's an error.
But why does the second one return first of July?
Is it a meant to be functional, in case you make a mistake it will "correct you"? Or is it a true bug in strtotime()?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you look at the docs for strtotime() you will see the first parameter is:

time
A date/time string. Valid formats are explained in Date and Time Formats.

If you follow the link for the date and time formats and go to Date Formats you will see:

enter image description here

Thus for the date format (I.e. DD), 01-31 is valid (since a 3 can only be followed by a 0 or 1) despite the month. Depending on the supplied month and date value the date will be adjusted.

Also found in the notes on that same page:

Note:
It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).1

Hence 06-31 is valid while 06-32 is invalid.

Additionally, in the User Contributed Notes section, the note by Mirek at 2015-04-01 01:14 might be useful/interesting:

Note: the day (dd or DD) is first checked for range 0..31 and only if it fits, the overflow and underflow mechanism may apply. If not, strtotime() simply returns false. If you need unlimited over/underflow for date calculations (for example 2015-01-40 to 2015-02-09), use mktime() instead.2


1http://php.net/manual/en/datetime.formats.date.php

2http://php.net/manual/en/datetime.formats.date.php#Hcom117014


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

...