简体   繁体   中英

How to save data in a different format in MySQL database

I notice that MySQL save date as 0000-00-00 format. But in my application I have validate date for this 00-00-0000 format. I notice that date is not saving properly as different formats. Can I change mysql data format to 00-00-0000 format?

The 00-00-0000 format is not entirely clear; it could be dd-mm-yyyy for instance.

You can simply convert the date you have like so:

$mydate = '24-12-2012';
// create date object by using a known format
// see manual page for all format specifiers
$d = DateTime::createFromFormat('d-m-Y', $mydate);

// format date object in yyyy-mm-dd
echo $d->format('Y-m-d'); 

See also: DateTime::createFromFormat() DateTime::format()

您还可以使用MySQL str_to_date函数

INSERT INTO yourtable (datefield) VALUES (str_to_date('01-02-2007', '%d-%m-%Y'));

As @Jack explained it is one of the correct way you can choose and

at the time of select date from database you can use DATE_FORMAT(date,format) .

You can't.
Instead of that you have to convert your custom format to database format and back.

To store it in the database you can use explode PHP function.
To when selecting, you can format mysql date format using DATE_FORMAT mysql function.

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