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

心已入冬 提交于 2019-12-02 22:40:23

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 ;)

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.

sysdate-(2/11)

To subtract hours from a DATE, you need to convert the hours in days. A day consists of 24 hours, so to convert 2 hours into days, you need to divide it by 24.

Now, to subtract 2 hours form the date, do:

DATE_value - 2/24

For example,

SQL> SELECT TO_CHAR(
  2                 TO_DATE('01/Jun/2015 00:00:00', 'DD/Mon/YYYY HH24:MI:SS') - 2/24,
  3         'DD/Mon/YYYY HH24:MI:SS') dt
  4  FROM DUAL;

DT
--------------------
31/May/2015 22:00:00

SQL>

date - n will subtract n days form given date. In order to subtract hrs you need to convert it into day buy dividing it with 24. In your case it should be to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24'). This will subract 2 days and 2 hrs from sysdate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!