【问题标题】:How to get the no of Days from the difference of two dates in PostgreSQL?如何从 PostgreSQL 中两个日期的差异中获取天数?
【发布时间】:2013-07-31 12:17:41
【问题描述】:
select extract(day from age('2013-04-06','2013-04-04'));`

给了我天数!即:2

但是当我有不同的月份时它失败了:

select extract(day from age('2013-05-02','2013-04-01'));

所以我需要得到32 days 的天数

【问题讨论】:

    标签: postgresql postgresql-9.1 postgresql-9.2


    【解决方案1】:

    减法似乎更直观。

    select '2013-05-02'::date - '2013-04-01'::date
    

    运行这个查询,看看为什么结果是 31 而不是 32

    with dates as (
      select generate_series('2013-04-01'::date, '2013-05-02'::date, '1 day')::date as end_date,
                             '2013-04-01'::date as start_date
    )
    select end_date, start_date, end_date - start_date as difference
    from dates
    order by end_date
    

    今天和今天之间的差异是零天。这是否重要取决于应用程序。如果需要,您可以添加 1。

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2011-01-30
      • 2022-01-01
      • 2022-12-01
      相关资源
      最近更新 更多