droptableifexists test cascade;createtable test(id serialprimarykey, time_info timestamp);-- 假设下面两条时间戳是业务上的传入的,而且是系统本地时区的时间(比如:北京时间, 北京时间相对于 UTC 时区时间, 相差 8 小时, 需要减去 8 小时 才等于 UTC 时区时间)insertinto test (time_info)values('2024-8-28 09:57:10'),('2024-8-28 10:57:13');select*from test;show TimeZone;
查看数据
postgres=# select * from test;
id | time_info
----+---------------------1|2024-08-2809:57:102|2024-08-2810:57:13(2rows)
postgres=#
postgres=#
postgres=# show TimeZone;
TimeZone
----------
UTC
(1row)
编写函数
--将本地时区时间转换为 UTC 时区时间
vim modify_local_timestmap_2_utc_based_timestamp.sqlCREATEORREPLACEFUNCTION func_modify_local_timestmap_2_utc_based_timestamp(delta_time varchar)RETURNSintAS
$BODY$
declareBEGINupdate test set time_info=time_info-delta_time::interval;RETURN0;END;
$BODY$
LANGUAGE'plpgsql' VOLATILE CALLED ONNULL INPUT SECURITY INVOKER;-- 调用函数, 参数值由 psql 命令行传入select*from func_modify_local_timestmap_2_utc_based_timestamp(:DELTA_TIME);
EOF