时区感知date_trunc函数

Jan*_*nis 16 postgresql timezone timezone-offset

以下查询

SELECT the_date FROM date_trunc('day', timestamp with time zone 
       '2001-01-1 00:00:00+0100') as the_date
Run Code Online (Sandbox Code Playgroud)

结果

the_date
2000-12-31 00:00
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉date_trunc根据它所用的时区进行日/月/年转换?

预期的产出是: 2001-01-1 00:00+0100

Clo*_*eto 17

您需要指定要在其中显示的时区

select
    date_trunc(
        'day',
        timestamp with time zone '2001-01-1 00:00:00+0100' at time zone '-02'
    ) as the_date;
      the_date       
---------------------
 2001-01-01 00:00:00
Run Code Online (Sandbox Code Playgroud)

AT TIME ZONE


Ada*_*ent 7

尽管标记的答案对于OP的怪异情况可能是正确的,但对于其他人则很可能是错误的。您需要将date_trunc返回的时间戳转换为正确的时区。

select
    date_trunc(
        'day',
        some_timestamp at time zone users_timezone
    ) at time zone users_timezone as the_date;
Run Code Online (Sandbox Code Playgroud)

要了解的重要一点是date_trunc返回timestamp没有附加时区的。您需要将时间戳转换为正确的时区,因为数据库客户端或任何下游客户端可能具有不同的时区。