date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

T_Conroy picture T_Conroy · Dec 13, 2013 · Viewed 109.7k times · Source

I unfortunately can't use DateTime() as the server this project is on is running PHP v.5.2.

the line in question:

$aptnDate2 = date('Y-m-d', $_POST['nextAppointmentDate']); 

throws the following error:

Notice: A non well formed numeric value encountered

so I var dump to make sure it's well formatted..

var_dump($_POST['nextAppointmentDate']);  

string(10) "12-16-2013"

The php docs state that it takes a timestamp not a string. but when I do:

date('Y-m-d', strtotime($_POST['nextAppointmentDate']));

and then var_dump the result, I get this:

string(10) "1969-12-31"

why can I not format a date with this date value and strtotime()?

thanks!

Answer

Amal Murali picture Amal Murali · Dec 13, 2013

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16