MySQL SQL日期格式转换?[dd.mm.yy 到 YYYY-MM-DD]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18597051/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:43:51  来源:igfitidea点击:

SQL date format convert? [dd.mm.yy to YYYY-MM-DD]

mysqlsqldateformatsql-function

提问by user2216190

is there mySQL function to convert a date from format dd.mm.yy to YYYY-MM-DD?

是否有将日期从格式 dd.mm.yy 转换为 YYYY-MM-DD 的 mySQL 函数?

for example, 03.09.13 -> 2013-09-03.

例如,03.09.13 -> 2013-09-03

回答by Ed Gibbs

Since your input is a string in the form 03.09.13, I'll assume (since today is September 3, 2013) that it's dd.mm.yy. You can convert it to a date using STR_TO_DATE:

由于您的输入是表单中的字符串03.09.13,我假设(因为今天是 2013 年 9 月 3 日)它是dd.mm.yy. 您可以使用STR_TO_DATE以下方法将其转换为日期:

STR_TO_DATE(myVal, '%d.%m.%y')

Then you can format it back to a string using DATE_FORMAT:

然后您可以使用DATE_FORMAT以下命令将其格式化回字符串:

DATE_FORMAT(STR_TO_DATE(myVal, '%d.%m.%y'), '%Y-%m-%d')

Note that the year is %y(lowercase "y") in STR_TO_DATEand %Y(uppercase "Y") in DATE_FORMAT. The lowercase version is for two-digit years and the uppercase is for four-digit years.

请注意,年份在%y(小写“y”)中STR_TO_DATE%Y(大写“Y”)在DATE_FORMAT. 小写版本表示两位数年份,大写版本表示四位数年份。

回答by Alma Do

Use

SELECT CONCAT(
'20',
SUBSTR('03.09.13', 7, 2),
'-',
SUBSTR('03.09.13', 4, 2),
'-',
SUBSTR('03.09.13', 1, 2))

Fiddle demo.

小提琴演示

More about formats you can read in the corresponding manual page. Tip: if this is about conversion value from non-datetime field - better to use DATE/DATETIME data type instead. However, this is a bad ideato operate with dates via string functions. Above there is a nice trick with STR_TO_DATE(will not repeat that code, updated to fit better)

您可以在相应的手册页中阅读有关格式的更多信息。提示:如果这是关于来自非日期时间字段的转换值 - 最好改用 DATE/DATETIME 数据类型。但是,通过字符串函数操作日期是一个坏主意。上面有一个很好的技巧STR_TO_DATE(不会重复该代码,更新以更好地适应)

回答by Gordon Linoff

Dates are stored using an internal format. You can use the function date_format()to convert it to a string using a variety of formats. For yours in particular:

日期使用内部格式存储。您可以使用该函数date_format()将其转换为各种格式的字符串。特别是对于您的:

select date_format(`date`, '%Y-%m-%d')