1.时间的变化
(1)时间的变化
select sysdate "当前时间",sysdate+1 "加一天",
sysdate+1/24 "加一时",
sysdate+1/24/60 "加一分",
sysdate+1/24/60/60 "加一秒" from dual
输出结果:
不过此种方法不能做月的加减,因为每月的天数不一样
(2)日期的变化
select sysdate "当前时间",add_months(sysdate,1) "加一个月",
add_months(sysdate,1*12) "加一年" from dual;
输出结果:
(3)使用numtoyminterval、numtodsinterval函数:
numtoyminterval:num to Y M interval;
numtodsinterval:num to D S interval
第三种函数功能还是比较强大的,但是拼写字母太多,用的比较少,毕竟前两种已经够用了。
select sysdate,sysdate + numtodsinterval(1,'second') "加一秒",
sysdate + numtodsinterval(1,'minute') "加一分",
sysdate + numtodsinterval(1,'hour') "加一小时",
sysdate + numtodsinterval(1,'day') "加一天",
sysdate + numtoyminterval(1,'month') "加一个月",
sysdate + numtoyminterval(1,'year') "加一年" from dual;
输出结果:
2. 获取两个时间的天数差
备注:当前时间是2019/7/8 10:23:49
select sysdate,sysdate - to_date('20190701','yyyymmdd') from dual;
输出:2019/7/8 10:23:49 | 7.43320601851852
select floor(sysdate - to_date('20190701','yyyymmdd')) from dual;--floor:向下取整
输出:7
select ceil(sysdate - to_date('20190701','yyyymmdd')) from dual;--ceil:向上取整
输出:8
select round(sysdate - to_date('20190701','yyyymmdd')) from dual;--round:四舍五入
输出:7
3. 计算两个时间的月份差
select months_between(to_date('20190708 111111','yyyy-mm-dd hh24:mi:ss'), to_date('20180708 233333','yyyy-mm-dd hh24:mi:ss')) from dual;
输出:12
select months_between(to_date('20190708','yyyy-mm-dd'),to_date('20180709','yyyy-mm-dd')) from dual;
输出:11.9677419354839
4.两个时间段的交集
(1) 获取有交集的记录1:
select * from oa_leave where end_time>=to_date('20190701','yyyymmdd') and start_time<=to_date('20190705','yyyymmdd');
(2) 获取有交集的记录2:
select * from oa_leave where (start_time,end_time) overlaps (to_date('20190701','yyyymmdd')-0.00001,to_date('20190705','yyyymmdd')+0.00001)--注:overlaps是开区间,一般使用方法1
输出结果:
(3) 求两个时间段的交集部分
select greatest(start_time,to_date('20190701','yyyymmdd')),least(end_time,to_date('20190705','yyyymmdd')) from oa_leave
where end_time>=to_date('20190701','yyyymmdd') and start_time<=to_date('20190705','yyyymmdd')
输出结果: