在oracle中,DATE可以使用减法找到两个s之间的差(以天和/或其分数为单位):
SELECT DATE '2016-03-23' - DATE '2015-12-25' AS difference FROM DUAL;
输出两个日期之间的天数:
DIFFERENCE ---------- 89
和:
SELECT TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ) AS difference FROM DUAL
输出两个日期之间的天数的分数:
DIFFERENCE ---------- 1.0425
以小时,分钟或秒差可以通过此数乘以中找到24,24*60或24*60*60分别。
可以将上一个示例更改为使用以下命令获取两个日期之间的天,小时,分钟和秒:
SELECT TRUNC( difference ) AS days, TRUNC( MOD( difference * 24, 24 ) ) AS hours, TRUNC( MOD( difference * 24*60, 60 ) ) AS minutes, TRUNC( MOD( difference * 24*60*60, 60 ) ) AS seconds FROM ( SELECT TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ) AS difference FROM DUAL
);
(注意:TRUNC()用于而非FLOOR()正确处理负差异。)
输出:
DAYS HOURS MINUTES SECONDS ---- ----- ------- ------- 1 1 1 12
前面的示例也可以通过使用以下方法将数值差转换为间隔来解决NUMTODSINTERVAL():
SELECT EXTRACT( DAY FROM difference ) AS days, EXTRACT( HOUR FROM difference ) AS hours, EXTRACT( MINUTE FROM difference ) AS minutes, EXTRACT( SECOND FROM difference ) AS seconds FROM ( SELECT NUMTODSINTERVAL( TO_DATE( '2016-01-02 01:01:12', 'YYYY-MM-DD HH24:MI:SS' ) - TO_DATE( '2016-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' ), 'DAY' ) AS difference FROM DUAL );