从字符串字段转换 MySQL 中的日期

2021-11-20 00:00:00 date mysql

我使用的系统将日期存储为 dd/mm/yyyy 格式的字符串.是否可以在 SELECT 查询中将其转换为 yyyy-mm-dd (以便我可以在其上使用 DATE_FORMAT )?MySQL 有日期解析功能吗?

I'm using a system where the dates are stored as strings in the format dd/mm/yyyy. Is it possible to convert this to yyyy-mm-dd in a SELECT query (so that I can use DATE_FORMAT on it)? Does MySQL have a date parsing function?

目前我能想到的唯一方法是连接一堆子字符串,但希望有一个更简单的解决方案.

Currently the only method I can think of is to concatenate a bunch of substrings, but hopefully there's a simpler solution.

(不幸的是,我无法将该字段转换为真正的日期字段,因为它是一个元表:同一列包含不同字段的值,而这些值只是字符串.)

(Unfortunately I can't convert the field to a true date field since it's a meta-table: the same column contains values for different fields that are just strings.)

推荐答案

这个:

STR_TO_DATE(t.datestring, '%d/%m/%Y')

...将字符串转换为日期时间数据类型.为了确保它以您想要的格式出现,请使用 日期格式:

...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:

DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')

如果你不能改变原始列的数据类型,我建议 创建视图 使用 STR_TO_DATE 调用将字符串转换为 DateTime 数据类型.

If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE call to convert the string to a DateTime data type.

相关文章