Oracle 日期相关

--查询某一天内的数据
select t.ID,t.LAST_TIME
		from T_ORDER t WHERE 
			--AND t.LAST_TIME >= to_date('2017-07-31 00:00:00','yyyy-mm-dd hh24:mi:ss') 
			t.LAST_TIME >= to_date('2017-07-31','yyyy-mm-dd') -- 2017-07-31 00:00:00
			--AND t.LAST_TIME <= to_date('2017-07-31 23:59:59','yyyy-mm-dd hh24:mi:ss')
			AND t.LAST_TIME < (to_date('2017-07-31','yyyy-mm-dd') + 1) -- 2017-08-01 00:00:00
;

--查询某一月内的数据
select t.ID,t.LAST_TIME
		from T_ORDER t WHERE 
			--AND two.LIMIT_LAST_TIME >= to_date('2017-07-01 00:00:00','yyyy-mm-dd hh24:mi:ss') 
			t.LAST_TIME >= to_date('2017-07','yyyy-mm') -- 2017-07-01 00:00:00
			--AND two.LIMIT_LAST_TIME <= to_date('2017-07-31 23:59:59','yyyy-mm-dd hh24:mi:ss')
			AND t.LAST_TIME < add_months(to_date('2017-07','yyyy-mm'), 1) -- 2017-08-01 00:00:00
;

--查询某一年内的数据
select t.ID,t.LAST_TIME
		from T_ORDER t WHERE 
			--AND two.LIMIT_LAST_TIME >= to_date('2017-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss') 
			t.LAST_TIME >= to_date('2017-01','yyyy-mm') -- 2017-01-01 00:00:00
			--AND two.LIMIT_LAST_TIME <= to_date('2017-12-31 23:59:59','yyyy-mm-dd hh24:mi:ss')
			AND t.LAST_TIME < to_date('2018-01','yyyy-mm') -- 2018-01-01 00:00:00
;

值得注意地:

--只转换年份,会得到当月1日的日期
select to_date('2017','yyyy') AS test from dual;--2017-07-01 00:00:00

 日期之间的差:

--两个日期相减为相差的天数:1
select (To_date('2017-07-05 09:00:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-04 09:00:00' , 'yyyy-mm-dd hh24-mi-ss')) AS test FROM DUAL; 
--两个日期相减为相差的天数:-0.5
select (To_date('2017-07-03 00:00:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-03 12:00:00' , 'yyyy-mm-dd hh24-mi-ss')) AS test FROM DUAL; 
--两个日期相差的小时:0.02
select (To_date('2017-07-04 09:01:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-04 09:00:00' , 'yyyy-mm-dd hh24-mi-ss')) * 24 AS test FROM DUAL; 
--两个日期相差的小时:1。ceil(n):取大于等于n的最小整数
select ceil((To_date('2017-07-04 09:01:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-04 09:00:00' , 'yyyy-mm-dd hh24-mi-ss')) * 24) AS test FROM DUAL; 
--两个日期相差的小时:0。floor(n):取小于等于n的最大整数
select floor((To_date('2017-07-04 09:01:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-04 09:00:00' , 'yyyy-mm-dd hh24-mi-ss')) * 24) AS test FROM DUAL; 
--两个日期相差的分钟:61.00
select (To_date('2017-07-04 10:01:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2017-07-04 09:00:00' , 'yyyy-mm-dd hh24-mi-ss')) * 24 * 60 AS test FROM DUAL; 

 值得注意地:两个日期不能直接相加。日期加数字,数字为天数。

 interval:(时间)间隔

--interval:(时间)间隔
select sysdate,',',interval '10' SECOND ,',',
	interval '10' MINUTE ,',',
	interval '10' HOUR ,',',
	interval '10' DAY ,',',
	interval '10' MONTH ,',',
	interval '10' YEAR  
from dual;
--2017-08-02 18:22:25, 0 0:0:10.0, 0 0:10:0.0, 0 10:0:0.0, 10 0:0:0.0, 0-10, 10-0

--当前时间减10分钟的时间
select sysdate,sysdate - interval '10' minute from dual;
--2017-08-02 18:08:03	2017-08-02 17:58:03

--当前时间加10分钟的时间
select sysdate,sysdate + interval '10' minute from dual;
--2017-08-02 18:08:37	2017-08-02 18:18:37

猜你喜欢

转载自tjy86.iteye.com/blog/2387804