在 SQLite 中向日期字段添加月份

问题描述 投票:0回答:1

我尝试通过运行以下查询向包含日期值的字段添加 3 个月:

SELECT  [Date Created], DATE([Date Created], '+3 month') AS 'Date Created (+ X Months)'
FROM WARRANTY_PN_MISSING_COMPATIBILITY_TABLE

似乎有些不对劲,事实上这是最终的结果: 在此输入图片描述

请问您能帮我解决这个问题吗?

谢谢

修复查询

sqlite
1个回答
0
投票

正如 @PanagiotisKanavos 在评论中指出的那样。您的日期格式不正确,Sqlite 无法接受它作为有效日期。话虽如此,解决方案是将字符串重新格式化为有效格式。如果可能的话,我建议使用保存数据的应用程序,如果不可能,您可以在选择查询中进行转换,如下所示:

(在本例中为

date
列)

SELECT 
    DATE( 
        SUBSTR(date , INSTR(SUBSTR(date, 4), '/') + 4, 4)  -- gets the year
        || '-' || 
        IIF(LENGTH (SUBSTR(date , 0,  INSTR(date, '/')) ) = 1, '0', '') || -- adds a leading Zero if needed
        SUBSTR(date , 0,  INSTR(date, '/')) -- gets the months 
        || '-' || 
        IIF(LENGTH(RTRIM(SUBSTR(date ,  INSTR(date, '/') + 1, 2) , '/') )= 1, '0', '') ||-- adds a leading Zero if needed
        RTRIM(SUBSTR(date ,  INSTR(date, '/') + 1, 2) , '/')  -- gets the days
        || SUBSTR(date , INSTR(date, ' ')) -- gets the time
        , '3 months') cleanDate
 FROM test ;

它并不优雅或高性能,但它应该适用于您的情况,其中存储的日期格式为“m/d/y 00:00:00”。 (如果时间部分缺少一些前导零,这可能是一个问题)

© www.soinside.com 2019 - 2024. All rights reserved.