PostgreSQL timestamp踩坑记录
项目Timezone情况
NodeJS:UTC+08
PostgreSQL:UTC+00
timestampTest.js
const { Client } = require('pg')
const client = new Client()
client.connect()
let sql = ``
client.query(sql, (err, res) => {
console.log(err ? err.stack : res.rows[0].datetime)
client.end()
})
不同时区to_timestamp查询结果
测试输入数据为1514736000
(UTC时间2017-12-31 16:00:00
,北京时间2018-01-01 00:00:00
)
1、timezone
=UTC
BEGIN;
SET TIME ZONE 'UTC';
SELECT to_timestamp(1514736000) as datetime;
END;
- 直接查询:
2017-12-31 16:00:00+00
YES - pg查询:
2017-12-31T16:00:00.000Z
YES
2、timezone
=PRC
BEGIN;
SET TIME ZONE 'PRC';
SELECT to_timestamp(1514736000) as datetime;
END;
- 直接查询:
2018-01-01 00:00:00+08
NO - pg查询:
2017-12-31T16:00:00.000Z
YES
PostgreSQL官方文档对timestamp的一个描述
详见:8.5.1.3. Time Stamps
In a literal that has been determined to be timestamp without time zone, PostgreSQL will silently ignore any time zone indication. That is, the resulting value is derived from the date/time fields in the input value, and is not adjusted for time zone.
坑
使用to_timestamp
进行时间转换且DB时区非UTC
时,写入**timestamp without time zone
**类型的COLUMN
则会与预期结果不符。
不同Timezone
/columnType
查询结果
1、 timezone
=UTC
,timestamp with timezone
BEGIN;
SET TIME ZONE 'UTC';
SELECT TIMESTAMP WITH TIME ZONE '2017-12-31T16:00:00+00' as datetime;
END;
- 直接查询:
2017-12-31 16:00:00+00
YES - pg查询:
2017-12-31T16:00:00.000Z
YES
2、 timezone
=UTC
,timestamp without timezone
BEGIN;
SET TIME ZONE 'UTC';
SELECT TIMESTAMP '2017-12-31T16:00:00+00' as datetime;
END;
- 直接查询:
2017-12-31 16:00:00
YES - pg查询:
2017-12-31T08:00:00.000Z
NO
3、 timezone
=PRC
,timestamp with timezone
BEGIN;
SET TIME ZONE 'PRC';
SELECT TIMESTAMP WITH TIME ZONE '2017-12-31T16:00:00+00' as datetime;
END;
- 直接查询:
2018-01-01 00:00:00+08
YES - pg查询:
2017-12-31T16:00:00.000Z
YES
4、 timezone
=PRC
,timestamp without timezone
BEGIN;
SET TIME ZONE 'PRC';
SELECT TIMESTAMP '2017-12-31T16:00:00+00' as datetime;
END;
- 直接查询:
2017-12-31 16:00:00
YES - pg查询:
2017-12-31T08:00:00.000Z
NO
据以上结果可判定:
使用pg
查询**timestamp without time zone
**类型的COLUMN
时,会将数据库存储的时间当做北京时间而非UTC时间,与数据库时区没有关系。
总结
网上类似问题的解决办法是将DB时区改为UTC+08
。
原理:写入DB的时间实际为北京时间,pg库恰好是当做北京时间读取,所以时间戳就不会出问题了。
假如应用部署在不同的地域,使用timestamp without time zone
存储timestamp
这样的设计简直是灾难。
不要用timestamp without time zone
存储timestamp
!
不要用timestamp without time zone
存储timestamp
!
不要用timestamp without time zone
存储timestamp
!
来源:oschina
链接:https://my.oschina.net/u/135537/blog/1795868