文章目录
- 常用函数与常量
- to_timestamp(字符串转时间戳、数字转时间戳)
- date与to_date(字符串转日期、时间戳转日期)
- interval(时间计算)
- to_char(各种时间转字符串)
- extract(提取时间字段,年月日时分秒,周、季度,第几周、第几天)
- date_part(类似extract)
- date_trunc(时间截断,计算特殊时间,一年第1天,一个季度第1天,一周最后1天等)
- 综合应用-时间计算
- 日期时间格式化字符串
常用函数与常量
函数
说明
current_time
现在的时间
current_date
今天的日期
current_timestamp
当前日期和时间
now()
当前的日期和时间和current_timestamp一样
localtime
time,当前时间
localtimestamp
当前日期和时间
timeofday()
字符串,当前日期和时间
age(timestamp1, timestamp2)
计算年纪,timestamp1-timestamp2,结果类型是interval,类似于:29 years 9 mons 27 days
select current_date,current_time,current_timestamp,now(),localtime,localtimestamp,timeofday();
select age('2030-04-10', '2000-06-13');
第1个参数减第2个参数,age返回值是interval,很方便算年龄
-- 时间戳转字符串再截取
SELECT now()::timestamp,substring(''||now()::timestamp from 1 for 19);
to_timestamp(字符串转时间戳、数字转时间戳)
函数
说明
to_timestamp(text, text)