Oracle中关于日期的总结

本文详细介绍Oracle数据库中关于时间处理的方法,包括时间格式转换、日期字符转换、查询具体日期及时间段数据、每周特定日数据检索等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在总结之前,先了解一下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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值