Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract hours from a date in Oracle so it affects the day also

I'm trying to subtract date from Oracle so it even effect the day as well. For example, if the timestamp is 01/June/2015 00 hours and if I subtract 2 hours, I want to be able to go to to 31/May/2014 22 hours.

I tried

to_char(sysdate-(2/11), 'MM-DD-YYYY HH24') 

but it only subtracts the hour; it does not touch the day itself.

like image 778
hi4ppl Avatar asked Jun 11 '15 05:06

hi4ppl


People also ask

How do I subtract hours in Oracle?

In Oracle, when you add or subtract a number to a date, the unit is days. So SYSDATE + 1 adds 1 day. To add some other increment, you just multiply or divide appropriately, i.e. SYSDATE - 1/24 subtracts an hour, SYSDATE - 1/24/60 subtracts a minute, etc.

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

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 . The first number you see is the number of whole days that passed from departure to arrival .

How do I subtract dates in Oracle?

In Oracle, you can subtract any number of days simply by subtracting that number from the current date. Here, since you need to subtract one day, you use current_date - 1 . Then you use the TO_DATE() function to cast the result to the column type date .

Can we compare date with TIMESTAMP in Oracle?

You can use the TO_DATE function. Convert both to timestamp and compare. This solution handles nulls as greatest will return null if one of the params is null.


2 Answers

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:

sysdate - interval '2' hour 

It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)

like image 150
a_horse_with_no_name Avatar answered Sep 28 '22 04:09

a_horse_with_no_name


Try this:

SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL 

To test it using a new date instance:

SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL 

Output is: 06-10-2015 22:00, which is the previous day.

like image 27
m3nation Avatar answered Sep 28 '22 05:09

m3nation