简体   繁体   English

如何在MySQL数据库中以其他格式保存数据

[英]How to save data in a different format in MySQL database

I notice that MySQL save date as 0000-00-00 format. 我注意到MySQL将日期保存为0000-00-00格式。 But in my application I have validate date for this 00-00-0000 format. 但是在我的应用程序中,我已经验证了该00-00-0000格式的日期。 I notice that date is not saving properly as different formats. 我注意到该日期未正确保存为其他格式。 Can I change mysql data format to 00-00-0000 format? 我可以将mysql数据格式更改为00-00-0000格式吗?

The 00-00-0000 format is not entirely clear; 00-00-0000格式不完全清楚; it could be dd-mm-yyyy for instance. 例如,可能是dd-mm-yyyy

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() 另请参见: 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 正如@Jack解释的那样,这是您可以选择并

at the time of select date from database you can use DATE_FORMAT(date,format) . 在从数据库中选择日期时,可以使用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. 要将其存储在数据库中,可以使用explode PHP函数。
To when selecting, you can format mysql date format using DATE_FORMAT mysql function. 选择时,可以使用DATE_FORMAT mysql函数格式化mysql日期格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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