這篇文章主要介紹PostgreSQL timestamp有哪些坑要注意一下,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
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() })
測試輸入數據為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+00YES
pg查詢:2017-12-31T16:00:00.000ZYES
2、timezone=PRC
BEGIN; SET TIME ZONE 'PRC'; SELECT to_timestamp(1514736000) as datetime; END;
直接查詢:2018-01-01 00:00:00+08NO
pg查詢:2017-12-31T16:00:00.000ZYES
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則會與預期結果不符。
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+00YES
pg查詢:2017-12-31T16:00:00.000ZYES
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:00YES
pg查詢:2017-12-31T08:00:00.000ZNO
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+08YES
pg查詢:2017-12-31T16:00:00.000ZYES
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:00YES
pg查詢:2017-12-31T08:00:00.000ZNO
據以上結果可判定:
使用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!
補充:pg查詢時間間隔(timestamp類型)
create_date timestamp(6) without time zone
1.從2015-10-12到2015-10-13 之間的4點到9點的數據
select * from schedule where create_date between to_date('2015-10-12','yyyy-MM-dd') and to_date('2015-10-13','yyyy-MM-dd') and EXTRACT(hour from create_date) between 4 and 9;
結果:
2.2015-10-12五點的數據
select * from schedule where hospital_id='syzyyadmin' and date_trunc('hour',create_date)=to_timestamp('2015-10-12 05','YYYY-MM-DD HH24')
結果:
以上是“PostgreSQL timestamp有哪些坑要注意一下”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。