Just another WordPress.com site

Posts tagged ‘time’

Time difference between two date columns

Solution 1

SQL> CREATE TABLE dates (date1 DATE, date2 DATE);

Table created.

SQL>
SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1);

1 row created.

SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1/24);

1 row created.

SQL> INSERT INTO dates VALUES (SYSDATE, SYSDATE-1/60/24);

1 row created.

SQL> SELECT (date1 - date2) FROM dates;

DATE1-DATE2
-----------
          1
 .041666667
 .000694444

Solution 2

SQL> SELECT floor(((date1-date2)*24*60*60)/3600)
2 || ' HOURS ' ||
3 floor((((date1-date2)*24*60*60) -
4 floor(((date1-date2)*24*60*60)/3600)*3600)/60)
5 || ' MINUTES ' ||
6 round((((date1-date2)*24*60*60) -
7 floor(((date1-date2)*24*60*60)/3600)*3600 -
8 (floor((((date1-date2)*24*60*60) -
9 floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60) ))
10 || ' SECS ' time_difference 11 FROM dates;
TIME_DIFFERENCE
--------------------------------------------------------------------------------
24 HOURS 0 MINUTES 0 SECS
1 HOURS 0 MINUTES 0 SECS 0
HOURS 1 MINUTES 0 SECS.

SQL> SELECT (date1 - date2) FROM dates;

DATE1-DATE2
-----------
          1
 .041666667
 .000694444

Solution 3

SQL> SELECT to_number( to_char(to_date('1','J') +
  2         (date1 - date2), 'J') - 1)  days,
  3         to_char(to_date('00:00:00','HH24:MI:SS') +
  4         (date1 - date2), 'HH24:MI:SS') time
  5   FROM dates;

      DAYS TIME
---------- --------
         1 00:00:00
         0 01:00:00
         0 00:01:00

Solution 4

NUMTODSINTERVAL: This function is new to Oracle 9i. It takes two arguments numtodsinterval(x,c) where x is a number and c is a character string denoting the units of x. Valid units are ‘DAY’, ‘HOUR’, ‘MINUTE’ and ‘SECOND’.

This function converts the number x into an INTERVAL DAY TO SECOND datatype.

SQL> select numtodsinterval(date1-date2,'day') time_difference from dates;

TIME_DIFFERENCE
----------------------------------------------------------------
+000000001 00:00:00.000000000
+000000000 01:00:00.000000000
+000000000 00:01:00.000000000

Solution 5

this works for both Date and timestamp columns

CREATE OR REPLACE FUNCTION datediff
( time1 TIMESTAMP,  time2 TIMESTAMP )
-- RETURN NUMBER
RETURN number
AS sec NUMBER;

BEGIN

SELECT (extract(DAY FROM time2-time1)*24*60*60)+
(extract(HOUR FROM time2-time1)*60*60)+
(extract(MINUTE FROM time2-time1)*60)+
extract(SECOND FROM time2-time1)
into sec FROM dual;

RETURN sec;

END;
Advertisements
%d bloggers like this: