谁能解释一下?当我希望它在我的本地 timezonw 中工作时,就好像 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;
如果我从 PSQL 运行函数SELECT fn_lib_now();
我在 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 调用该函数:
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'