1、年月日加减法,获取n天前后,n年前后时间
select sysdate-5 as hd_minus_5D,--五天前的当前时间
sysdate+5 as hd_plus_5D,--五天后
add_months(sysdate,-5) as hd_minus_5M,--五月前
add_months(sysdate,5) as hd_plus_5M,--五月后
add_months(sysdate,-5*12) as hd_minus_5Y,--五年前
add_months(sysdate,5*12) as hd_plus_5Y--五年后
from dual;
2、计算两个日期之间的天数、月份和年份
--查询结果都为小数,使用时注意根据实际需求取舍
select (sysdate - date '2022-4-1')*24*60*60 --2022-4-1到当前时间相差秒数
(sysdate - date '2022-4-1')*24*60,--2022-4-1到当前时间相差分钟数
(sysdate - date '2022-4-1')*24,--2022-4-1到当前时间相差小时数
sysdate - date '2022-4-1', --2022-4-1到当前时间相差天数
months_between(sysdate, date '2022-3-15'),--2022-3-15到当前时间相差月份
months_between(sysdate, date '2022-3-15') / 12--2022-3-15到当前时间相差年份
from dual;
3、计算两个日期之间的工作日天数
--计算2021-4-1到2021-4-15之间的工作日数(即出去周六周日)
select sum(decode(to_char(dates, 'DY'), '星期六', 0, '星期日', 0, 1)) as days
from (SELECT TO_DATE('2021-4-01', 'yyyy-MM-dd') + ROWNUM - 1 dates
FROM DUAL
CONNECT BY ROWNUM <=
trunc(to_date('2021-4-15', 'yyyy-MM-dd') -
to_date('2021-4-01', 'yyyy-MM-dd')) + 1)
4、统计一年每个星期出现的次数
--近一年每周出现次数
with x as
(select level lvl
from dual
connect by level <=
(add_months(trunc(sysdate, 'y'), 12) - trunc(sysdate, 'y')))
select to_char(trunc(sysdate, 'y') + lvl - 1, 'DAY'), count(*)
from x
group by to_char(trunc(sysdate, 'y') + lvl - 1, 'DAY')
5、判断是否闰年
--获取二月的天数
select to_char(last_day(add_months(trunc(sysdate, 'y'), 1)), 'DD')
from dual --若二月为29天闰年
6、计算一年有多少天
select add_months(trunc(sysdate,'y'),12) - trunc(sysdate,'y')
from dual
7、从给定日期值里提取年月日时分秒星期
--从给定日期值里提取年月日时分秒
select to_number(to_char(sysdate, 'hh24')) hour, --当前时间小时
to_number(to_char(sysdate, 'mi')) min, --当前时间分钟
to_number(to_char(sysdate, 'ss')) sec, --当前时间秒
to_number(to_char(sysdate, 'dd')) day, --当前时间天
to_char(sysdate, 'day'), --当前时间星期
to_number(to_char(sysdate, 'mm')) mth, --当前时间月
to_number(to_char(sysdate, 'yyyy')) year --当前时间年
from dual
8、计算一个月的第一天和最后一天
select trunc(sysdate,'mm') firstday,
last_day(sysdate) lastday
from dual
9、列出一年中所有的星期五的日期
with x
as (
select trunc(sysdate,'y')+level-1 dy
from dual
connect by level <=
add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y')
)
select *
from x
where to_char( dy, 'dy') = '星期五'
10、找出当前月份的第一个和最后一个星期一
select next_day(trunc(sysdate,'mm')-1,'星期一') first_monday,
next_day(last_day(trunc(sysdate,'mm'))-7,'星期一') last_monday
from dual
11、生成当前月份日历
with x
as (
select *
from (
select to_char(trunc(sysdate,'mm')+level-1,'iw') wk,
to_char(trunc(sysdate,'mm')+level-1,'dd') dm,
to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,
to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,
to_char(sysdate,'mm') mth
from dual
connect by level <= 31
)
where curr_mth = mth
)
select max(case dw when 2 then dm end) Mo,
max(case dw when 3 then dm end) Tu,
max(case dw when 4 then dm end) We,
max(case dw when 5 then dm end) Th,
max(case dw when 6 then dm end) Fr,
max(case dw when 7 then dm end) Sa,
max(case dw when 1 then dm end) Su
from x
group by wk
order by wk