简体   繁体   English

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

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

is there mySQL function to convert a date from format dd.mm.yy to YYYY-MM-DD? 是否有mySQL函数将格式dd.mm.yy转换为YYYY-MM-DD?

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

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 . 由于您的输入是03.09.13形式的字符串,因此我假设(自今天起是2013年9月3日)它是dd.mm.yy You can convert it to a date using STR_TO_DATE : 您可以使用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_DATE and %Y (uppercase "Y") in DATE_FORMAT . 请注意,年份是STR_TO_DATE %y (小写“y”)和DATE_FORMAT %Y (大写“Y”)。 The lowercase version is for two-digit years and the uppercase is for four-digit years. 小写版本为两位数年份,大写版本为四位数年份。

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. 提示:如果这是关于非日期时间字段的转换值 - 请更好地使用DATE / DATETIME数据类型。 However, this is a bad idea to 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) STR_TO_DATE上面有一个很好的技巧(不会重复该代码,更新以更好地适应)

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. 您可以使用函数date_format()将其转换为使用各种格式的字符串。 For yours in particular: 特别为你的:

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

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

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