记录一下 pg中使用的函数to_timestamp,date_trunc,to_char
一、函数to_timestamp
函数用于将字符串String按照format格式转换为timestamp with time zone类型(时间戳格式)
SELECT to_timestamp('2023-05-10 19:08:00.678', 'YYYY-MM-DD HH24:MI:SS.MS');
-- 2023-05-10 19:08:00.678+08
-- HH24表示24小时制的小时,MI表示分钟,SS表示秒数,MS表示毫秒数
二、函数date_trunc
函数用于将timestamp,timestamp with time zone ,date,time或者interval数据截断到指定的精度。
项目中暂时用到
select date_trunc('month',current_date)
-- 2023-05-01 00:00:00+08
select date_trunc('month',current_date)::DATE
-- 2023-05-01
SELECT date_trunc('year', timestamp '2020-03-03 20:38:40')
-- 2020-01-01 00:00:00
SELECT date_trunc('minute', interval '2 days 3 hours 40 minutes');
-- 2 days 03:40:00
三、函数to_char
to_char(expre,format)函数用于将timestamp,inteval,integer,double precision,或者numeric类型的值转换为指定格式的字符串。
select to_char(interval '10h 36m 30s', 'HH12:MI:SS')
-- 10:36:30
select to_char(CURRENT_TIMESTAMP ,'HH24:MI:SS' )
-- 10:37:32