-2

I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25. Is there anyone can help me in this??

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Hardik
  • 1,429
  • 2
  • 19
  • 37

4 Answers4

2

The 31th April don't exist. Because of that PHP going to the day after the 30th April

1

April only has 30 days, so it's actually correcting the date your using. The 31st would really be the 1st of May.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Its wrong with input, not with date().

$data['toDate'] = "2017-04-31";// no 31st in 4th(April) month
echo $data['toDate'] ." : ". date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

Its just showing up next date which is 01-05-2017

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

tl;dr

04-31 is valid but not technically a date in April, since April only has 30 days and thus strtotime() yields 05-01.

Documentation

If you look at the documentation 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 04-31 is valid but overflows.

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

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58