【问题标题】:How to Find the Interval Between Two Dates in PostgreSQL如何在 PostgreSQL 中查找两个日期之间的间隔
【发布时间】:2021-04-02 20:10:26
【问题描述】:

我在 Postgres DB 的“测试”表中有一个“测试日期”列,例如 - (2018-05-29)

我需要计算当前日期与该日期列之间的差异,并将结果返回为天、月、年。

我试过了-

select (current_date - test_date) from test;

但它以天为单位返回值。但我需要几天、几个月、几年的结果。 如何正确转换?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    age() 函数以间隔而不是天数的形式返回值:

    select age(current_date, test_date) 
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    如果您使用timestamp,那么您将得到一个“间隔”:

    select justify_interval(date_trunc('day', current_timestamp) - test_date)
    

    date_trunc() 用于将时间戳的时间部分设置为00:00:00。默认情况下,这将返回一个只有几天的时间间隔。然后justify_interval() 会将其“标准化”为月、周和天。

    例如0 years 7 mons 28 days 0 hours 0 mins 0.0 secs

    【讨论】:

    • 非常感谢!有了这个我可以很容易地根据要求标准化间隔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2018-02-13
    • 2023-04-10
    • 2015-08-06
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多