我尝试返回特定时区的值,并且我在回应时遇到了一些奇怪的行为:
SELECT created_at AT TIME ZONE 'US/Pacific' - created_at,
NOW() AT TIME ZONE 'US/Pacific' - NOW(),
NOW() now FROM "my_table"
ORDER by id DESC LIMIT 1
返回
10:00:00 | -10:00:00 | 2017-08-02 17:36:30.660477+03
为什么同一函数会从表中返回相反的值(-10 / + 10)以及动态时间?
谢谢!
答案 0 :(得分:3)
类型timestamp without timezone
被解释为“本地时区”
因此,您的created_at AT TIME ZONE 'US/Pacific'
值将被视为给定时区的时间戳。
NOW()
返回timestamp with timezone
,因此您的NOW() AT TIME ZONE 'US/Pacific'
值必须转换为其他时区。
参见文档:
试试这个:
SELECT created_at AT TIME ZONE 'US/Pacific' AS crated_at_us_pacific, created_at,
NOW() AT TIME ZONE 'US/Pacific' AS now_us_pacific, NOW() AS now
FROM "my_table"
ORDER by id DESC
LIMIT 1
答案 1 :(得分:0)
感谢Usagi Miyamoto的一些澄清,它让我走上正轨。
如果没有时区AT TIME ZONE的字段时间戳定义了特定的时区。所以首先声明localtime然后将其转换为特定的时区:所以修复的SQL是:
SELECT created_at AT TIME ZONE 'localtime' AT TIME ZONE 'US/Pacific' - created_at,
NOW() AT TIME ZONE 'US/Pacific' - NOW(),
NOW() now FROM "my_table"
ORDER by id DESC LIMIT 1
修改强>
更动态
SELECT created_at::timestamptz AT TIME ZONE 'US/Pacific' - created_at,
NOW() AT TIME ZONE 'US/Pacific' - NOW(),
NOW() now FROM "my_table"
ORDER by id DESC LIMIT 1
首先timestamptz
将时间转换为当地时区,然后转换为您需要的时区AT TIME ZONE 'US/Pacific'