In my controller, when I create
an event, it saves perfectly fine. The user enters a date in dd-mm-yyyy
and it gets saved in MySQL DATETIME
format. Then the details
view renders it completely fine, just like the edit
view via model binding.
As soon as I try to save from the edit
form, the date somehow fails and returns 1970-01-01 00:00:00
.
I am not really sure why this only happens on my update
method, as my store
method is in essence the same.
$input = Input::all();
$input['plannedTime'] = date('Y-m-d H:i:s', strtotime(Input::get('plannedTime')));
How comes the update
method returns no error, validation is alright, but it still won't save it correctly?
The value of 'plannedTime' is a string of date format d-m-Y H:i:s.
There's your problem. PHP's strtotime
does its best, but 04-05-2015 00:00:00
could be either April 5 or May 4, depending where you live.
As an example, on my install, strtotime('04-13-2014 00:00:00')
fails (which'll get converted to 0, which'll get converted to 1970-01-01).
Laravel's date
validation expects a value that strtotime can handle. If you're using an ambiguous date format, use createFromFormat
to parse it, then format
to spit it out in a more standard format.
$date = DateTime::createFromFormat('d-m-Y H:i:s', Input::get('plannedTime'));
$usableDate = $date->format('Y-m-d H:i:s');
MySQL never returns any error for invalid dates as far as i can remember, it just sets it to EPOCH and thats it!
You should enforce your dates to be always converted to a "Y-m-d H:i:s" format when communicating with your site and display the date in "d-m-Y" only on the output side.
You should try and use
public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
To create a datetime object from a format. If you know your format such as in this case, then provide the format and get a date object back which will be persisted correctly!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With