drop table if exists test cascade;
create table test(id serial primary key, time_info timestamp);
-- 假设下面两条时间戳是业务上的传入的,而且是系统本地时区的时间(比如:北京时间, 北京时间相对于 UTC 时区时间, 相差 8 小时, 需要减去 8 小时 才等于 UTC 时区时间)
insert into test (time_info) values('2024-8-28 09:57:10'),('2024-8-28 10:57:13');
select * from test;
show TimeZone;
查看数据
sql复制代码
postgres=# select * from test;
id | time_info
----+---------------------
1 | 2024-08-28 09:57:10
2 | 2024-08-28 10:57:13
(2 rows)
postgres=#
postgres=#
postgres=# show TimeZone;
TimeZone
----------
UTC
(1 row)
编写函数
sql复制代码
--将本地时区时间转换为 UTC 时区时间
vim modify_local_timestmap_2_utc_based_timestamp.sql
CREATE OR REPLACE FUNCTION func_modify_local_timestmap_2_utc_based_timestamp(delta_time varchar)
RETURNS int
AS
$BODY$
declare
BEGIN
update test set time_info=time_info-delta_time::interval;
RETURN 0;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
-- 调用函数, 参数值由 psql 命令行传入
select * from func_modify_local_timestmap_2_utc_based_timestamp(:DELTA_TIME);
EOF