oracle中两个日期之间的差异

时间:2014-01-14 11:58:34

标签: sql oracle datetime oracle10g

如何找到oracle中两个日期之间的区别?

我尝试使用Extract方法,但效果不正常。

格式应为 hh:mm:ss

1 个答案:

答案 0 :(得分:1)

EXTRACT适用于日期时间或间隔值表达式。当您减去两个日期时,您会得到一个数字,即天数。如果你想使用 提取你应该使用NUMTODSINTERVAL将其转换为区间数据类型,然后使用EXTRACT。

SELECT   TO_DATE ('14-01-2014 14:00:00', 'dd-mm-yyyy hh24:mi:ss')
       - TO_DATE ('13-01-2014 22:30:45', 'dd-mm-yyyy hh24:mi:ss')
  FROM DUAL;

0.6453125

SELECT NUMTODSINTERVAL (
            TO_DATE ('14-01-2014 14:00:00', 'dd-mm-yyyy hh24:mi:ss')
          - TO_DATE ('13-01-2014 22:30:45', 'dd-mm-yyyy hh24:mi:ss'),
          'DAY')
  FROM DUAL;

+00 15:29:15.000000

SELECT    EXTRACT (HOUR FROM intrvl)
       || ':'
       || EXTRACT (MINUTE FROM intrvl)
       || ':'
       || EXTRACT (SECOND FROM intrvl)
  FROM (SELECT NUMTODSINTERVAL (
                    TO_DATE ('14-01-2014 14:00:00', 'dd-mm-yyyy hh24:mi:ss')
                  - TO_DATE ('13-01-2014 22:30:45', 'dd-mm-yyyy hh24:mi:ss'),
                  'DAY')
                  AS intrvl
          FROM DUAL);

15:29:15

您甚至可以将日期转换为时间戳,以便差异已经是interval数据类型。

SELECT    EXTRACT (HOUR FROM intrvl)
       || ':'
       || EXTRACT (MINUTE FROM intrvl)
       || ':'
       || EXTRACT (SECOND FROM intrvl)
  FROM (SELECT   CAST (
                    TO_DATE ('14-01-2014 14:00:00', 'dd-mm-yyyy hh24:mi:ss') AS TIMESTAMP)
               - CAST (
                    TO_DATE ('13-01-2014 22:30:45', 'dd-mm-yyyy hh24:mi:ss') AS TIMESTAMP)
                  AS intrvl
          FROM DUAL);