to_date()
select sysdate,to_date('2018-3-20','yyyy-mm-dd') from dual;
select sysdate,to_date('2018-3-20','yyyy.mm.dd') from dual;
select sysdate,to_date('2018-3-20','yyyy/mm/dd') from dual;
select sysdate,to_date('2018-3-20','yyyy-mm-dd hh24:mi:ss') from dual;
select sysdate,to_date('2018.3.20','yyyy-mm-dd') from dual;
select sysdate,to_date('2018/3/20','yyyy-mm-dd') from dual;
select sysdate,to_date('20180320','yyyy-mm-dd') from dual;
运行结果:
无论是日期是什么格式,还是’yyyy-dd-mm’是什么格式,其结果都和系统日期格式保持一致。得到的时间为2018/3/20。
时分秒格式:
select to_date('2019-01-01 10:20:30','yyyy-mm-dd hh24:mi:ss') from dual;
运行结果:
时间作为条件判断的赋值
第一种情况:字段内容带有时分秒,输入的数据没有时分秒
select h.creation_date from demo h where h.creation_date > to_date('2019-01-01','yyyy-mm-dd')
运行结果:
有数据,时分秒的字段是可以和不带时分秒的字段比较。
第二种情况:输入的数据按时分秒去匹配:
select * from demo t where t.creation_date > to_date('2019-01-01 10:20:30','yyyy-mm-dd hh24:mi:ss')
运行结果:
第三种情况:将字段内容转换成没有时分秒,输入参数没有时分秒
select to_date(to_char(fcv.creation_date,'yyyy-mm-dd'),'yyyy-mm-dd')
from demo fcv
where to_date(to_char(fcv.creation_date,'yyyy-mm-dd'),'yyyy-mm-dd') > to_date('2019-01-01','yyyy-mm-dd')
and fcv.creation_date < sysdate;
第四种情况:将字段内容转换成没有时分秒,输入参数有时分秒
select to_date(to_char(fcv.creation_date, 'yyyy-mm-dd'), 'yyyy-mm-dd')
from demo fcv
where to_date(to_char(fcv.creation_date, 'yyyy-mm-dd'), 'yyyy-mm-dd') >
to_date('2019-01-01 10:20:30', 'yyyy-mm-dd hh24:mi:ss')
and fcv.creation_date < sysdate;
结果一样的。只要是保证时间类型对应时间类型就可以。
to_char()
将时间日期按照指定的格式输出,得到的是字符串,而非date类型。
select sysdate,to_char(sysdate,'yyyy-mm-dd')from dual;
select sysdate,to_char(sysdate,'yyyy/mm/dd')from dual;
select sysdate,to_char(sysdate,'yyyymmdd')from dual;
select sysdate,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')from dual;
运行结果:
2019-05-14
2019/05/14
20190514
2019-05-14 11:43:26
熟练使用to_date()和to_char()的集合使用。