MySQL mysql更改日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9426993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql change date format
提问by mustafa
I have a date field (tinytext) holding date information in format of "dd-mm-yy" e.g 07-01-90. Using a mysql query I want to change it to yyyy-mm-dd date format. I tried the code below but nothing happens.
我有一个日期字段(tinytext),以“dd-mm-yy”格式保存日期信息,例如 07-01-90。使用 mysql 查询,我想将其更改为 yyyy-mm-dd 日期格式。我尝试了下面的代码,但没有任何反应。
mysql_query("UPDATE Table SET date=STR_TO_DATE('date','%Y,%m,%d')");
回答by Taz
You're using the correct function STR_TO_DATE(str,format)
to achieve the goal, but you're making two mistakes:
您正在使用正确的功能STR_TO_DATE(str,format)
来实现目标,但您犯了两个错误:
- In your query the
format
argument does not match the string expression format. You said it's indd-mm-yy
format while you passed%Y,%m,%d
(comma separated) to theformat
argument. The query will return a "incorrect datetime value" error. You should use%d-%m-%Y
. - You can't change data type of a column on the fly, by setting different type of the value being passed. You have to first update the values and then change data type for column.
- 在您的查询中,
format
参数与字符串表达式格式不匹配。您在dd-mm-yy
将%Y,%m,%d
(逗号分隔)传递给format
参数时说它是格式的。查询将返回“不正确的日期时间值”错误。你应该使用%d-%m-%Y
. - 您不能通过设置不同类型的传递值来动态更改列的数据类型。您必须首先更新值,然后更改列的数据类型。
So, summarizing:
所以,总结一下:
mysql_query("UPDATE `Table` SET `date` = STR_TO_DATE(`date`, '%d-%m-%Y')");
mysql_query("ALTER TABLE `Table` CHANGE COLUMN `date` `date` DATE");
Additionally, consider switching to the recommended PDOextension in place of old and slowly deprecatedmysql
extension.
回答by Naveen Kumar
Error in your query
您的查询出错
is STR_TO_DATE(date, '%Y-%m-%d')
是 STR_TO_DATE(日期,'%Y-%m-%d')
mysql_query("UPDATE Table SET date=STR_TO_DATE(date,'%Y-%m-%d')");
回答by Karan
Try this:
尝试这个:
INSERT INTO table(date_field) VALUES(STR_TO_DATE('December 8, 2010','%M %d,%Y'));
回答by Fahim Parkar
To display 2digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%y-%m-%d')");
To display 4digit year
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y-%m-%d')");
显示2位数年份
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%y-%m-%d')");
显示4位数年份
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y-%m-%d')");
回答by Korhan Ozturk
Try it with DATE_FORMAT()function.
尝试使用DATE_FORMAT()函数。
mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y,%m,%d')");
回答by helle
I'd say you have to do this:
我会说你必须这样做:
UPDATE table_name SET date = DATE_FORMAT('date', %Y-%m-%d);