Postgre获取本周、本月和本年日期函数

根据当前时间获取当前周、当前月 和当前年的开始时间

SELECT * FROM (
--当前时间
SELECT 'now' as type, CURRENT_DATE as time
UNION ALL
--本周开始时间
SELECT 'week' as type, CURRENT_DATE - (extract(DOW from CURRENT_DATE) || ' day')::interval as time
UNION ALL
--本月开始时间
SELECT 'month' as type, to_date(to_char(now(),'yyyy-mm-01'),'yyyy-mm-dd') as time
UNION ALL
--本年开始时间
SELECT 'year' as type, to_date(to_char(now(),'yyyy-01-01'),'yyyy-mm-dd') as time 
) t1

Postgre获取本周、本月和本年日期函数_第1张图片

 

其中获取本周时间用到了extract(DOW from CURRENT_DATE)函数,该函数用于获取当前时间是本周的第几天,时间从周日开始,到周六结束。

--获取星期几
SELECT * from (
SELECT 'Sun' as week, extract(DOW from TIMESTAMP'2019-08-04') 
UNION ALL
SELECT 'Mon' as week, extract(DOW from TIMESTAMP'2019-08-05') 
UNION ALL
SELECT 'Tues' as week, extract(DOW from TIMESTAMP'2019-08-06') 
UNION ALL
SELECT 'Wed' as week, extract(DOW from TIMESTAMP'2019-08-07') 
UNION ALL
SELECT 'Thur' as week, extract(DOW from TIMESTAMP'2019-08-08') 
UNION ALL
SELECT 'Fri' as week, extract(DOW from TIMESTAMP'2019-08-09') 
UNION ALL
SELECT 'Sat' as week, extract(DOW from TIMESTAMP'2019-08-10') 
) t1

Postgre获取本周、本月和本年日期函数_第2张图片

你可能感兴趣的:(Sql)