8. Date Arithmetic

Adding and Subtracting Days, Months, and Years

We need to add or subtract some number of days, months, or years from a date

-- Oracle
select 
    hiredate-5 as hd_minus_5D,
    hiredate+5 as hd_plus_5D,
    add_months(hiredate,-5) as hd_minus_5M,
    add_months(hiredate,5) as hd_plus_5M,
    add_months(hiredate,-5*12) as hd_minus_5Y,
    add_months(hiredate,5*12) as hd_plus_5Y
from emp
where deptno = 10

Determining the Number of Days Between Two Dates

We want to find the difference between two dates and represent the result in days.

For example, use two inline views to find the HIREDATEs for WARD and ALLEN, and then subtract one date from the other

Determining the Number of Business Days Between Two Dates

We want to find how many “working” days are between 2 dates, including the 2 dates themselves.

Output of SELECT TO_DATE(level - 1 + TO_CHAR(TO_DATE('2024-05-28', 'YYYY-MM-DD'), 'YYYYDDD'), 'YYYYDDD') AS calendar_date FROM DUAL CONNECT BY LEVEL <= TRUNC(TO_DATE('2024-05-31', 'YYYY-MM-DD')) - TRUNC(TO_DATE('2024-05-28', 'YYYY-MM-DD')) + 1

Determining the Number of Months or Years Between Two Dates

We want to find the difference between two dates in terms of either months or years.

Determining the Number of Seconds, Minutes, or Hours Between Two Dates

We want to return the difference in seconds between two dates.

Counting the Occurrences of Weekdays in a Year

We want to count the number of times each weekday occurs in one year.

To find the number of occurrences of each weekday in a year:

  1. Generate all possible dates in the year.

  2. Format the dates such that they resolve to the name of their respective weekdays.

  3. Count the occurrence of each weekday name.

Determining the Date Difference Between the Current Record and the Next Record

We want to determine the difference in days between two dates (specifically dates stored in two different rows).

Last updated