简体   繁体   English

如何从 Oracle 中的日期中减去小时数,因此它也会影响当天

[英]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.我正在尝试从 Oracle 中减去日期,因此它甚至也会影响这一天。 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.例如,如果时间戳是 01/June/2015 00 小时,如果我减去 2 小时,我希望能够转到 31/May/2014 22 小时。

I tried我试过

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

but it only subtracts the hour;但它只减去小时; it does not touch the day itself.它不涉及这一天本身。

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.其他人评论了(错误的)使用2/11来指定所需的间隔。

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:然而,我个人更喜欢使用 ANSI interval文字编写类似的东西,这使得阅读查询更容易:

sysdate - interval '2' hour

It also has the advantage of being portable, many DBMS support this.它还具有可移植的优点,许多 DBMS 都支持这一点。 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.输出为:06-10-2015 22:00,即前一天。

sysdate-(2/11)系统日期-(2/11)

A day consists of 24 hours .一天由24 hours组成。 So, to subtract 2 hours from a day you need to divide it by 24 :因此,要从一天中减去2 hours ,您需要将其除以24

DATE_value - 2/24

Using interval for the same:使用interval相同:

DATE_value - interval '2' hour

date - n will subtract n days form given date. date - n将从给定日期减去 n 天。 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') .为了减去小时,您需要将其转换为日买除以 24。在您的情况下,它应该是to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24') This will subract 2 days and 2 hrs from sysdate.这将从 sysdate 减去 2 天 2 小时。

you should divide hours by 24 not 11你应该把小时除以 24 而不是 11
like this:像这样:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM