首页 > 解决方案 > 为什么 postgres 使用不同的时区进行格式化?

问题描述

我正在使用我的 JS 代码运行以下查询pg

SELECT begin_at, to_char(begin_at, 'DD.MM') AS dt
FROM tasks
WHERE begin_at >= $1
ORDER BY begin_at

begin_at有类型timestamptz

在我的 PC 上,我在我的时区 (UTC+4) 中获得日期, { begin_at: "2021-11-02T19:00:00.000Z", dt: "03.11" }在服务器上我获得{ begin_at: "2021-11-02T19:00:00.000Z", dt: "02.11" }相同数据库的日期。

两者都在运行node v16.8.0postgres 13都具有相同的时间并将 postgres 时区设置为Asia/Yekaterinburg

标签: node.jspostgresqltimezone

解决方案


该列begin_at很可能是在没有时区的情况下声明的,或者会话具有不同的时区。自己看看区别:

SET TIMEZONE = 'Asia/Yekaterinburg';
SELECT to_char('2021-11-02T19:00:00.000Z'::timestamp with time zone, 'DD.MM');

 to_char 
---------
 03.11

无时区:

SET TIMEZONE = 'Asia/Yekaterinburg';
SELECT to_char('2021-11-02T19:00:00.000Z'::timestamp, 'DD.MM');

 to_char 
---------
 02.11

为了确保会话的timezone您可能想尝试SHOW TIMEZONE

SHOW TIMEZONE;

 TimeZone 
----------
 Etc/UTC

查看这个demo,看看SET TIMEZONE在seesion中的效果:db<>fiddle


推荐阅读