【问题标题】:How to add number of days in postgresql datetime如何在 postgresql 日期时间中添加天数
【发布时间】:2012-06-10 05:08:28
【问题描述】:

我有一个下表projects

id title        created_at               claim_window
1  Project One  2012-05-08 13:50:09.924  5
2  Project Two  2012-06-01 13:50:09.924  10

A) 我想通过计算deadline = created_at + claim_window(No. of days) 找到截止日期。

如下所示。

id title        created_at               claim_window  deadline
1  Project One  2012-05-08 13:50:09.924  5             2012-05-13 13:50:09.924
2  Project Two  2012-06-01 13:50:09.924  10            2012-06-11 13:50:09.924

B) 我也想找到截止日期已过的项目

id title        created_at               claim_window  deadline
1  Project One  2012-05-08 13:50:09.924  5             2012-05-13 13:50:09.924

我尝试以下类似的方法。

SELECT * FROM "projects" 
WHERE (DATE_PART('day', now()- created_at) >= (claim_window+1))

但由于某种原因它不起作用。

【问题讨论】:

    标签: postgresql datetime


    【解决方案1】:

    这将为您提供最后期限:

    select id,  
           title,
           created_at + interval '1' day * claim_window as deadline
    from projects
    

    也可以使用函数make_interval

    select id,  
           title,
           created_at + make_interval(days => claim_window) as deadline
    from projects
    

    要获取截止日期已过的所有项目,请使用:

    select *
    from (
      select id, 
             created_at + interval '1' day * claim_window as deadline
      from projects
    ) t
    where localtimestamp at time zone 'UTC' > deadline
    

    【讨论】:

    • 但又出现了一个问题,我的 created_at 的数据类型为 timestamp without time zone 而 current_timestamp 的数据类型为 timestamp with time zone,因此我没有得到正确的答案
    • @Salil: LOCALTIMESTAMPtimestamp without time zone
    • @Salil:也无所谓,timestamptimestamptz 的结果都是一样的,只要数据指的是同一时间点。添加一天对两者的效果相同。
    • 我的 create_at 保存在 UTC 时间(无时区)中,而 LOCALTIMESTAMP 和 CURRENT_TIMESTAMP 给了我 +5.30 的时间,因此问题仍然没有得到解决
    • @Salil:然后使用localtimestamp at time zone 'UTC'重新计算本地时间戳到UTC
    【解决方案2】:

    对我来说,我必须将整个区间放在单引号中,而不仅仅是区间的值。

    select id,  
       title,
       created_at + interval '1 day' * claim_window as deadline from projects   
    

    代替

    select id,  
       title,
       created_at + interval '1' day * claim_window as deadline from projects   
    

    Postgres Date/Time Functions

    【讨论】:

    • created_at + '1 day' 也对我有用。
    【解决方案3】:

    您可以使用以下代码添加或减去任何日期字段

    select date('08/30/2021') + 180 ---它将给出下一个 180 天的日期

    选择 current_date + 180 ---它将给出下一个 180 天的日期

    选择 current_date - 180 ---它会在 180 天之前给出日期

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-27
      • 2019-10-30
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多