为什么Rails会将从Postgres函数返回的时间更改为UTC?

时间:2013-05-07 09:56:23

标签: ruby-on-rails timezone rails-postgresql

任何人都能解释一下吗?就好像Rails正在重写Postgres并告诉它在UTC工作时我想让它在我当地的时间中工作吗?

我有一个Postgres函数,它返回如下的本地时间:

CREATE OR REPLACE FUNCTION fn_lib_now() RETURNS TIMESTAMP AS $$
DECLARE
l_now TIMESTAMP;
BEGIN
l_now = LOCALTIMESTAMP;

-- Debug code that writes to local file
DROP TABLE IF EXISTS x;
CREATE TABLE x (a TEXT);
INSERT INTO x (a) VALUES (l_now);
COPY (SELECT x.a AS localnow, LOCALTIMESTAMP AS local_timestamp, LOCALTIMESTAMP::date         AS local_date, LOCALTIME AS local_time, CURRENT_DATE AS current_date, CURRENT_TIME AS current_time FROM x) TO 'C:\temp\a.txt' WITH CSV HEADER;

-- Success
RETURN l_now;
END;
$$ LANGUAGE plpgsql;

如果我使用SELECT fn_lib_now();

从PSQL运行该函数

我在PSQL中得到结果:`“2013-05-07 18:59:43.916”``(正确的当地时间)

我的调试输出(重新格式化)是:

localnow,                 local_timestamp,           local_date,    local_time,      current_date,  current_time
2013-05-07 18:59:43.916,  2013-05-07  18:59:43.916,  2013-05-07,   18:59:43.916,    2013-05-07,    18:59:43.916+10

请注意,返回的所有时间都与当地时间相符。

但是,如果我使用Rails调用Rails中的函数:

begin
  result = (self.class.find_by_sql(["SELECT fn_lib_now() AS nowout"])).first
rescue ActiveRecord::WrappedDatabaseException => e
  raise self.class.handle_sql_error(e)
end
puts result[:nowout]

我得到了返回值:'2013-05-07 09:11:10.142'

我的调试输出(重新格式化)是:

localnow,                  local_timestamp,         local_date,  local_time,     current_date,  current_time
2013-05-07 09:11:10.142,  2013-05-07 09:11:10.142,  2013-05-07,  09:11:10.142,     2013-05-07,    09:11:10.142+00

请注意,所有时间都与UTC相匹配(比澳大利亚时区落后10小时)。

为什么在从PSQL(本地时间)和Rails(UTC)调用时,相同的函数会返回不同的结果,尤其是当我的application.rb包含以下行时:

config.time_zone = 'Brisbane'

0 个答案:

没有答案