Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: subtract millisecond from a datetime

Tags:

I thought it was really simple but it isn't.

SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY')            - 1/(24*50*60*1000) data  FROM dual; 

It simply doesn't work.


Other details:

SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') -            NUMTODSINTERVAL(1/(24*50*60*1000),'HOUR') data  FROM dual; 

doesn't work..

The right seems to be

SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') -            NUMTODSINTERVAL(1/(24*25*60*1000),'HOUR') data  FROM dual; 

Why? How does it work?

like image 445
Revious Avatar asked Aug 10 '12 11:08

Revious


People also ask

How can I find the difference between two timestamps in Oracle seconds?

To calculate the difference between the timestamps in Oracle, simply subtract the start timestamp from the end timestamp (here: arrival - departure ). The resulting column will be in INTERVAL DAY TO SECOND .

Does Oracle date have milliseconds?

Dates do not contain milliseconds, they only go as fine as seconds. You might want to try a timestamp datatype. Valid date range from January 1, 4712 BC, to December 31, 9999 AD.

Can you subtract dates in SQL Oracle?

Date – dateYou can subtract a date from a date in Oracle. The result will be in days. You can also multiply by 24 to get hours and so on.

Is date function in Oracle SQL?

Date functions in Oracle can be defined as a set of functions which operate on date and allows the developer or users to retrieve the current date and time in a particular time zone or extract only the date/ month/year or more complex actions like extracting the last day of the month/ next day/ session time zone and it ...


2 Answers

For adding or subtracting an amount of time expressed as a literal you can use INTERVAL.

SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY')      - INTERVAL '0.001' SECOND  FROM dual; 

As well there are now standard ways to express date and time literals and avoid the use of various database specific conversion functions.

SELECT TIMESTAMP '2012-10-08 00:00:00'     - INTERVAL '0.001' SECOND DATA FROM dual; 

For your original question the time part of a day is stored in fractional days. So one second is:

1 / (hours in day * minutes in hour * seconds in a minute) 

Divide by 1000 to get milliseconds.

1 / (24 * 60 * 60 * 1000) 
like image 97
Brian Avatar answered Oct 14 '22 17:10

Brian


SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') - NUMTODSINTERVAL(1/(24*50*60*1000),'HOUR') data  FROM dual; 

OUTPUT

DATA                              --------------------------------- 09/AUG/12 11:59:59.999950000 PM    1 row selected. 
like image 38
Gaurav Soni Avatar answered Oct 14 '22 15:10

Gaurav Soni