背景
有時候需要利用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