Oracle中关于日期的总结

在总结之前,先了解一下Oracle关于时间的一些参数方法
a. 时间的一般格式:yyyy-mm-dd hh24:mi:ss
b. 将日期转换成字符:to_char(m.create_date,‘yyyy-mm-dd hh24:mi:ss’)
c. 将字符转换成日期:to_date(‘2019-05-31’,‘yyyy-mm-dd hh24:mi:ss’)
d. 将某一天/月/年转换成数字:to_number(to_char(m.create_date,‘dd’)),
to_number(to_char(m.create_date,‘mm’)),to_number(to_char(m.create_date,‘yyyy’))
e. 当前时间 sysdate,前一天 sysdate-1;
f. 每周的开始时间是周日,判断周几用 to_number(to_char(sysdate,‘D’)),周日为1,周六为7;

1. 查找具体某一天的数据
select * from msg_announce m where to_char(m.create_date,‘yyyy-mm-dd’) = ‘2019-05-05’;
注意:
select * from msg_announce m where to_char(m.create_date,‘yyyy-mm-dd’) = ‘2019-5-05’; 和 select * from msg_announce m where to_char(m.create_date,‘yyyy-mm-dd’) = ‘2019-05-5’; 都是查不出来的,用这种方法要记得格式的统一;
以上的查询还可通过以下的SQL语句来实现:
select * from msg_announce m
where to_number(to_char(m.create_date,‘yyyy’)) = 2019
and to_number(to_char(m.create_date,‘mm’)) = 5
and to_number(to_char(m.create_date,‘dd’)) = 5
这里通过将字符转换成整数类型,避免05和5之间不能转换,开发时可灵活运用。
拓展:这里不仅可以确定到某一天,某一月,某一年或某一小时某一分钟都行。

2. 查找某个时间段的数据
select * from msg_announce m
where m.create_date between to_date(‘2019-04-01’,‘yyyy-mm-dd’)
and to_date(‘2019-05-31’,‘yyyy-mm-dd’)
或者
select * from msg_announce m
where m.create_date >= to_date(‘2019-04-01’,‘yyyy-mm-dd’)
and m.create_date <= to_date(‘2019-05-31’,‘yyyy-mm-dd’)
在这里的2019-04-01转换成2019-4-1之后,仍可查询,由此需要注意的是,在将参数进行不同数据类型转换时,记得判断是否因数据类型的转换而使值不相同;
由此还可拓展至前7天,前15天等的数据即:
select * from msg_announce m
where m.create_date >= sysdate - 7

3. 查询一段时间内每周三的数据
select * from msg_announce m
where to_number(to_char(m.create_date,‘D’)) = 4
and m.create_date between to_date(‘2019-04-01’,‘yyyy-mm-dd’)
and to_date(‘2019-05-31’,‘yyyy-mm-dd’)
由此可拓展至每月的几号,每年的几月,即
to_number(to_char(m.create_date,‘mm’)) = 4 每年四月
to_number(to_char(m.create_date,‘dd’)) = 2 每月二号

  1. 查询上个月第一天 00:00:00 和最后一天23:59:59 的时间
--00:00:00点默认不显示
select to_date(to_char(add_months(last_day(sysdate)+1,-2),'yyyy-MM-dd') || ' 00:00:00','yyyy-MM-dd hh24:mi:ss') firstDay from dual;

select to_date(to_char(add_months(last_day(sysdate),-1),'yyyy-MM-dd') || ' 23:59:59','yyyy-MM-dd hh24:mi:ss')  LastDay from dual;

猜你喜欢

转载自blog.csdn.net/qq_42740899/article/details/90241841