Strtotime on wrong dates

I found something strange in strtotime ().

On dates that do not exist, he returns the next day.

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

$d31= strtotime("2017-06-31");
Echo $d31 ."\n";
Echo date("Y-m-d", $d31)."\n\n";  // 2017-07-01

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

      

https://3v4l.org/AjMAE

I understand the latter. It returns nothing as it is an error.
But why did the second come back in July?
Should it function, if you are wrong it will "fix you"? Or is it a bug in strtotime ()?

+3


source to share


2 answers


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

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

If you follow the link for Date and Time Formats and navigate to Date Formats , you will see:

enter image description here

Thus, 01-31 is valid for the date format (Ie DD) (since 3 can only be followed by 0 or 1), regardless of the month. Depending on the delivery month and date, the date will be adjusted.

Also found in the notes on the same page:

Note :
Possible overflow and invalid dd and DD format. Day 0 means the last day of the previous month, and overflow means the next month. This means that "2008-08-00" is equivalent to "2008-07-31" and "2008-06-31" is equivalent to "2008-07-01" (June only has 30 days). 1



Therefore 06-31 is valid, but 06-32 is incorrect.

Also, the User Contributed Notes section by Mirek at 2015-04-01 01:14 might be helpful / interesting:

Note: the day (dd or DD) is first checked for the range 0..31 and only if it is appropriate can the overflow and downstream mechanism be applied. If not, strtotime () simply returns false. If you need unlimited overflow / underflow to calculate the date (e.g. 2015-01-40 - 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

+6


source


As far as the day of the 31

month is possible strtotime()

, you will correct the date for you. If you try it from February (2017-02-31) it will correct the value 2017-03-03

. This is what you found.

So what it basically does:

  • get date
  • check if date is in valid range (days per month)
  • if the day count is invalid next month


This behavior is implemented in the function itself strtotime

.

There was a great comment on the documentation page about this, but I can't find it anymore. This comment contains additional information (be sure to check the link in the comment).

+3


source







All Articles