背景
有时候需要利用sql中处理关于时间的判别问题,简单的如比较时间的早晚,判断一个时间是否在一段时间内的问题等。如果简单将时间判断与数值比较等同,那就会出现一些问题。
处理方式
处理Sql时间范围的问题有两种比较方式。
当前时间
select to_char(sysdate,\'yyyy-mm-dd hh24:mi:ss\') as Nowtime from dual;
//2020-04-02 16:25:42
1、将日期转换为字符串再比较
select sysdate nowtime from dual where to_char(sysdate,\'yyyymmdd hh24:mi:ss\') between \'20200401\' and \'20200403\';
//02-APR-20,时间范围是2020-04-01 00:00:00 至 2020-04-03 00:00:00
select sysdate time from dual where to_char(sysdate,\'yyyymmdd\') between \'20200402\' and \'20200402\'; //02-APR-20,时间范围是2020-04-02 00:00:00 至 2020-04-02 24:00:00
2、将字符串转化为日期再比较
select sysdate nowtime from dual where sysdate between to_date(\'20200401\',\'yyyyMMdd\') and to_date(\'20200403\',\'yyyyMMdd\');
//02-APR-20,时间范围是2020-04-01 00:00:00 至 2020-04-03 00:00:00
注意:如果不在字符串中指定时间则转换的时间默认为0点,所以前后日期一致则时间间隔为0。
select to_char(to_date(\'20200402\',\'yyyyMMdd\'),\'yyyyMMdd hh24:mi:ss\') nowtime from dual; //20200402 00:00:00