mySQL 将 varchar 转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4706289/
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 convert varchar to date
提问by webdad3
I need to convert a varchar value of 1/9/2011 to a date in mySQL and I want only the month and year. So that I can then use the PERIOD_DIFF
function (so I would need the above to be converted to 201101).
我需要将 1/9/2011 的 varchar 值转换为 mySQL 中的日期,我只需要月份和年份。这样我就可以使用该PERIOD_DIFF
函数(因此我需要将上述内容转换为 201101)。
I've tried various ways using the STR_TO_DATE
function:
我尝试了各种使用该STR_TO_DATE
函数的方法:
SELECT STR_TO_DATE(CYOApp_oilChangedDate, '%m/%Y') FROM CYO_AppInfo
But I get weird results... (for example: 2009-01-00)
但我得到了奇怪的结果......(例如:2009-01-00)
What am I doing incorrectly?
我做错了什么?
回答by Jon Black
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');
or
或者
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
hard to tell from your example
很难从你的例子中看出
回答by mbkhan
As gratitude to the timely help I got from here - a minor update to above.
感谢我从这里得到的及时帮助 - 对上面的一个小更新。
$query = "UPDATE `db`.`table` SET `fieldname`= str_to_date( fieldname, '%d/%m/%Y')";