timezone aware date_trunc function

橙三吉。 提交于 2019-12-23 06:55:23

问题


The following query

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

results to

the_date
2000-12-31 00:00

Is there a way to tell date_trunc to do day/month/year conversions based on the timezone it is feeded with?

The expected output would be: 2001-01-1 00:00+0100


回答1:


You need to specify at which time zone you want it to show

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

AT TIME ZONE




回答2:


While the marked answer might be correct for the OP's weird circumstances it is more likely incorrect for others. You need to convert the timestamp returned by date_trunc to the proper timezone.

select
    date_trunc(
        'day',
        some_timestamp at time zone users_timezone
    ) at time zone users_timezone as the_date;

The important thing to understand is date_trunc returns a timestamp with no timezone attached to it. You need to convert the timestamp to the proper timezone because the database client or whatever downstream might have a different timezone.




回答3:


@Adam's answer is definitely more helpful. Although I think we can improve on it again because if we're truncating a Timestamp to a single day (or week/month/etc), then we want to make sure that we're dealing with a Date object, not a Timestamp. Otherwise we may give other pieces of code the impression that something just actually happened to occur at midnight (or potentially some other misleading time of day).

So I would use:

SELECT date_trunc('day', some_timestamp AT TIME ZONE users_timezone)::date AS the_date;

which casts the result to a Date, rather than Timestamp.

The result will be something like:

  the_date
------------
 2019-09-14

instead of the more misleading result of:

      the_date
---------------------
 2019-09-14 00:00:00


来源:https://stackoverflow.com/questions/24040039/timezone-aware-date-trunc-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!