Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding Oracle SYSDATE to the nearest hour

Tags:

sql

oracle

Supposing the current SYSDATE is 03-APR-17 03.35.49, my query would need to get values between:

a. SYSDATE rounded to nearest passed hour (in this case 03.00.00)

b. a minus 1 hour = 02.00.00

I have tried and found that using "-1/24" returns the date time with an hour subtracted. Kinda new to Oracle so struggling on the first part. Not sure if I should be using ROUND or FLOOR or any other functionality. Any help appreciated.

like image 295
Adi Avatar asked Apr 03 '17 20:04

Adi


People also ask

How do you subtract hours from Sysdate?

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.

What is the difference between Sysdate and Systimestamp?

Need to convert SYSTIMESTAMP and SYSDATE to variables, which pass values in the format acceptable to Oracle. In Oracle, SYSTIMESTAMP is a keyword that returns the system timestamp of the Oracle server. Likewise, SYSDATE is a keyword that returns the system date of the Oracle server.


2 Answers

select sysdate,
       trunc(sysdate, 'hh') as truncated,
       round(sysdate, 'hh') as rounded
from   dual;

SYSDATE              TRUNCATED            ROUNDED
-------------------  -------------------  -------------------
04/03/2017 15:54:22  04/03/2017 15:00:00  04/03/2017 16:00:00
like image 196
mathguy Avatar answered Nov 04 '22 00:11

mathguy


This is to truncate the value:

select trunc(sysdate, 'hh')
from dual;

To round it:

select trunc(sysdate + interval '30' minute, 'hh')
from dual;

Or:

select round(sysdate, 'hh')
from dual;

I forget that round() can also take a format argument.

like image 43
Gordon Linoff Avatar answered Nov 04 '22 01:11

Gordon Linoff