Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: saving date to MySQL

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?

like image 935
jbehrens94 Avatar asked Apr 15 '15 19:04

jbehrens94


2 Answers

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');
like image 76
ceejayoz Avatar answered Oct 13 '22 13:10

ceejayoz


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!

like image 35
Mathieu Dumoulin Avatar answered Oct 13 '22 11:10

Mathieu Dumoulin