Skip to content
Advertisement

How to return 14th day from month which was 2 months ago with determinated time in Oracle SQL?

How can I take the 14th day from month which was 2 months ago with time 23:59:59 in Oracle SQL ? I have query like below and I need answer something like below (similar style):

select to_char(to_date(LAST_DAY(ADD_MONTHS(sysdate, -2)), 'YY-MM-DD'), 'YY/MM/DD) from dual

Above query return: 21/12/31, nevertheless I need query like above which will return value: '21/12/14 23:59:59'

Advertisement

Answer

You can use:

SELECT ADD_MONTHS(TRUNC(sysdate, 'MM'), -2)
         + INTERVAL '13 23:59:59' DAY TO SECOND  AS day
FROM   DUAL

Which outputs:

DAY
2021-12-14 23:59:59

If you want formatted with a specific format then use TO_CHAR:

SELECT TO_CHAR(
         ADD_MONTHS(TRUNC(sysdate, 'MM'), -2)
           + INTERVAL '13 23:59:59' DAY TO SECOND,
         'YYYY-MM-DD HH24:MI:SS'
       ) AS day
FROM   DUAL

db<>fiddle here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement