简体   繁体   中英

php convert date to mysql format

I have gone through convert php date to mysql format but still I have few issues and questions,

In general, my application, can input dates in Ymd , dmy , mdY , jS , FY format, or even with '/' separator.

I want this dates to be converted in to MYSQL Ymd format, I tried as below, but it shows different output than expected,

Non working

date_format(date_create_from_format('d-m-Y', '02-25-2016'), 'Y-m-d');

Working

date_format(date_create_from_format('d-m-Y', '25-02-2016'), 'Y-m-d');

So it seems format and string to be match in same way, otherwise its not interpreting correctly,

What is best way to convert above 4 format inputs to mysql(Ymd) format?

Thanks advanced,

I'd recommend using Carbon for any date processing in PHP these days.

Creating date by parsing strings is simple enough...
http://carbon.nesbot.com/docs/#api-instantiation

Getting the output in a format you need is also simple...
http://carbon.nesbot.com/docs/#api-formatting

I'd suggest you to use this function: DateTime::createFromFormat

Using this, you need to create a date by specifying the particular format.

Try this:

 $date = DateTime::createFromFormat('Y-m-d', '2016-05-26');
 echo $date->format('Y-m-d');
 echo "<hr/>";

 $date = DateTime::createFromFormat('d-m-Y', '26-05-2016');
 echo $date->format('Y-m-d');
 echo "<hr/>";

 $date = DateTime::createFromFormat('m-d-Y', '05-26-2016');
 echo $date->format('Y-m-d');
 echo "<hr/>";

 $date = DateTime::createFromFormat('jS F Y', '26th May 2016');
 echo $date->format('Y-m-d');

Thanks for all suggestions, i think i found my logic, My date format selection is stored in sql db, so will try as below,

date_format(date_create_from_format('format from db', 'user entered format'), 'Y-m-d');

As user entered format is stored in db, so i will pull that in this date_format function, so both will match and i can convert to Ymd!

Thanks,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM