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

1

28

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!

Antipodal answered 13/12, 2013 at 19:29 Comment(0)
B
64

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
Bayle answered 13/12, 2013 at 19:32 Comment(2)
Cheers mate, that was it. I could have sworn dashes were acceptable, perhaps that is just with DateTime()? Thank you for your help. :)Antipodal
@Prefix: If you pass an incorrectly formatted date string to DateTime, it will (usually) throw an exception. See the documentation for a list of accepted date formats. If you're using DateTime, then DateTime::createFromFormat() is the way to go: eval.in/79189Bayle

© 2022 - 2024 — McMap. All rights reserved.