PostgreSQL - 如何在不同时区呈现日期? [英] PostgreSQL - how to render date in different time zone?
问题描述
我的服务器在中部时间.我想使用东部时间呈现时间戳.
例如,我想将 2012-05-29 15:00:00
呈现为 2012-05-29 16:00:00 EDT
.p>
我怎样才能实现它?
to_char('2012-05-29 15:00:00'::timestamptz at time zone 'EST5EDT', 'YYYY-MM-DD HH24:MI:SS TZ')
给出 2012-05-29 16:00:00
(无区).
to_char('2012-05-29 15:00:00'::timestamp at time zone 'EST5EDT', 'YYYY-MM-DD HH24:MI:SS TZ')
给出 <代码>2012-05-29 14:00:00 CDT(错误).
这个可行,但它非常复杂,必须有一种更简单的方法:replace(replace(to_char(('2012-05-29 15:00:00'::timestamptz at time zone 'EST5EDT')::timestamptz, 'YYYY-MM-DD HH24:MI:SS TZ'), 'CST', 'EST'), 'CDT', 'EDT')
关键是切换本地时区到想要显示的时区,在事务的持续时间内:
开始;将本地时区设置为EST5EDT";select to_char('2012-05-29 15:00:00'::timestamp at time zone 'CDT','YYYY-MM-DD HH24:MI:SS TZ');结尾;
结果是:
<块引用>2012-05-29 16:00:00 EDT
请注意,使用 set [local] timezone
需要使用完整的时区名称而不是缩写(例如,CST 不起作用).在 pg_timezone_names
视图中查找有效选择.
要在类似于 to_char() 调用的上下文中使用该方法,我相信这个函数可以完成这项工作:
创建函数 display_in_other_tz(in_t 时间戳,in_tzname 文本,in_fmt text) 返回文本作为$$宣布v 文本;save_tz 文本;开始在 save_tz 中显示时区;EXECUTE '将本地时区设置为' ||报价文字(in_tzname);选择 to_char(in_t, in_fmt) INTO v;EXECUTE '将本地时区设置为' ||quote_literal(save_tz);返回 v;结尾;$$ 语言 plpgsql;
My server is in Central Time. I would like to render timestamps using Eastern time.
For instance, I would like to render 2012-05-29 15:00:00
as 2012-05-29 16:00:00 EDT
.
How can I achieve it?
to_char('2012-05-29 15:00:00'::timestamptz at time zone 'EST5EDT', 'YYYY-MM-DD HH24:MI:SS TZ')
gives 2012-05-29 16:00:00
(no zone).
to_char('2012-05-29 15:00:00'::timestamp at time zone 'EST5EDT', 'YYYY-MM-DD HH24:MI:SS TZ')
gives 2012-05-29 14:00:00 CDT
(wrong).
This one works, but it's so ridiculously complicated there must be an easier way: replace(replace(to_char(('2012-05-29 15:00:00'::timestamptz at time zone 'EST5EDT')::timestamptz, 'YYYY-MM-DD HH24:MI:SS TZ'), 'CST', 'EST'), 'CDT', 'EDT')
The key is to switch the local timezone to the desired display timezone, for the duration of the transaction:
begin;
set local timezone to 'EST5EDT';
select to_char('2012-05-29 15:00:00'::timestamp at time zone 'CDT',
'YYYY-MM-DD HH24:MI:SS TZ');
end;
The result is:
2012-05-29 16:00:00 EDT
Note that with set [local] timezone
it is required to use full time zone names instead of abbreviations (for instance, CST would not work). Look up in the pg_timezone_names
view for valid choices.
To use that method in a context similar to a to_char() call, I believe this function does the job:
CREATE FUNCTION display_in_other_tz(
in_t timestamptz,
in_tzname text,
in_fmt text) RETURNS text
AS $$
DECLARE
v text;
save_tz text;
BEGIN
SHOW timezone into save_tz;
EXECUTE 'SET local timezone to ' || quote_literal(in_tzname);
SELECT to_char(in_t, in_fmt) INTO v;
EXECUTE 'SET local timezone to ' || quote_literal(save_tz);
RETURN v;
END;
$$ language plpgsql;
这篇关于PostgreSQL - 如何在不同时区呈现日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!