0

我想将组日期(天+小时)转换为用户时区以显示列表,我不想更新数据库。我有几个小组,这段代码非常慢。

# GROUP.RB
# day  -> Date
# hour -> Time
# wday -> Integer
.
.
groups.each do |g|
    new_day = g.in_gmt_day(user_time_zone) # <-- Concat group.day with group.hour and convert the result day with the user time zone.
    g.wday = new_day.wday
    g.hour = new_day
end
.
.

任何人都可以帮助我吗?

谢谢。

4

1 回答 1

1

让 Postgres 为你做这件事:

SELECT (day + hour) AT TIME ZONE '<source tz>' AT TIME ZONE 'localtime'
FROM   groups;

这确实

  1. timestamp [without time zone]从两列数据类型中创建一个,date并且time(假设这里的问题对确切的数据类型含糊不清):

    day + hour
    
  2. 将此时间戳设置为源的时区,我们以“欧洲/伦敦”为例。结果为timestamp with time zone(或timestamptz简称):

    (day + hour) AT TIME ZONE 'Europe/London'
    
  3. 显示等效的 local timestamp [without time zone]

    (day + hour) AT TIME ZONE 'Europe/London' AT TIME ZONE 'localtime'
    

从这里你可以对这个值做任何事情,比如一次又一次地分割,或者用你喜欢的任何方式格式化它to_char()

WITH x AS (
   SELECT (day + hour) AT TIME ZONE 'Europe/London' AT TIME ZONE 'localtime' AS ts
   FROM   groups
   )
SELECT ts::date AS day, ts::time AS hour, to_char(ts, 'HH24') AS h24
FROM   x;
于 2012-08-23T15:05:11.600 回答