SQLite中如何将文本日期转为日期类型并修改显示格式
SQLite中文本日期格式转换方案
针对你存储为"5/24/2023"格式的文本日期列,要转换为"2023-05-24"标准格式,可通过SQLite的字符串处理函数实现,以下是具体方案:
1. 查询转换(仅查看结果,不修改原表)
使用substr截取日期各部分,结合printf格式化补零,确保月、日为两位数字:
SELECT printf('%04d-%02d-%02d', -- 提取年份(第二个/之后的部分) substr(date_col, instr(date_col, '/', instr(date_col, '/') + 1) + 1), -- 提取月份(第一个/之前的部分) substr(date_col, 1, instr(date_col, '/') - 1), -- 提取日期(两个/之间的部分) substr(date_col, instr(date_col, '/') + 1, instr(date_col, '/', instr(date_col, '/') + 1) - instr(date_col, '/') - 1) ) AS formatted_date FROM your_table;
2. 更新原表(直接修改列值)
如果需要将转换后的日期永久保存到原列,执行以下更新语句:
UPDATE your_table SET date_col = printf('%04d-%02d-%02d', substr(date_col, instr(date_col, '/', instr(date_col, '/') + 1) + 1), substr(date_col, 1, instr(date_col, '/') - 1), substr(date_col, instr(date_col, '/') + 1, instr(date_col, '/', instr(date_col, '/') + 1) - instr(date_col, '/') - 1) );
注意事项
- 替换
your_table为你的实际表名,date_col为目标日期列名; - 执行更新前务必先通过SELECT语句验证转换结果,建议备份数据后再操作;
- 该方案兼容单/双位数的月、日格式(比如
"5/4/2023"会转为"2023-05-04"); - 若存在非
M/D/YYYY或MM/DD/YYYY格式的异常数据,需先过滤或单独处理。
内容的提问来源于stack exchange,提问作者Alex Wright
相关产品推荐
相关产品推荐

