seco's avatar
Level 1

save date to db regardless of format

i want to make a page that save the date field regardless of the format i use the following code

 $model->date = date('Y-m-d', strtotime(trim(str_replace('/','-',$request->date))));

when the date is in format of d/m/Y it saves well BUT when i change the date format to m/d/Y it saves the date as 01/01/1970 !!!

i want a unified code to save date to db regardless of its format

thanks in advance.

0 likes
3 replies
spekkionu's avatar

From the documentation for the strtotime function

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. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

By replacing the separator you are telling it to use d-m-y format. If you want either to be handled remove the str_replace.

jekinney's avatar
jekinney
Best Answer
Level 47

Use carbon either create or parse. Carbon has this functionality already to take a date string in most formats and create a date object ready for MySQL. And Laravel uses it out of the box.

1 like
spekkionu's avatar

Carbon extends the core DateTime object.

The date parsing Carbon does is just a wrapper over the DateTime constructor which is the same parsing done by the http://php.net/manual/en/function.strtotime.php function so there isn't a difference in what dates you would get by using Carbon vs. the core php functions/objects. You do get a much nicer / more readable api though so I'd still recommend it.

For more information on what formats Carbon/DateTime/strtotime can handle take a look at the php docs.

http://php.net/manual/en/datetime.formats.php

Please or to participate in this conversation.