timezone aware date_trunc function

后端 未结 3 1880
逝去的感伤
逝去的感伤 2021-01-07 20:14

The following query

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

resu

3条回答
  •  耶瑟儿~
    2021-01-07 20:27

    @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
    

提交回复
热议问题