9. Date Manipulation

Determining Whether a Year Is a Leap Year

We want to determine whether the current year is a leap year.

Check the last day of February and if it is the 29th, then the current year is a leap year.

select to_char(
    last_day(add_months(trunc(sysdate,'y'),1)),
    'DD')
from t1

Determining the Number of Days in a Year

We want to count the number of days in the current year

select add_months(trunc(sysdate,'y'),12) - trunc(sysdate,'y') from dual

Extracting Units of Time from a Date

We want to break the current date down into day, month, year, second, minute, and hour.

select to_number(to_char(sysdate,'hh24')) hour,
  to_number(to_char(sysdate,'mi')) min,
  to_number(to_char(sysdate,'ss')) sec,
  to_number(to_char(sysdate,'dd')) day,
  to_number(to_char(sysdate,'mm')) mth,
  to_number(to_char(sysdate,'yyyy')) year
from dual

Determining the First and Last Days of a Month

We want to determine the first and last days for the current month

Determining All Dates for a Particular Weekday Throughout a Year

We want to find all the dates in a year that correspond to a given day of the week. For example, generate a list of Fridays for the current year.

Determining the Date of the First and Last Occurrences of a Specific Weekday in a Month

We want the first and last Mondays of the current month as an example.

Creating a Calendar

We want to create a calendar for the current month.

Listing Quarter Start and End Dates for the Year

We want to return the start and end dates for each of the four quarters of a given year.

Determining Quarter Start and End Dates for a Given Quarter

We want to return the quarter’s start and end dates, for a given year and quarter in the format of YYYYQ (four-digit year, one-digit quarter).

Searching on Specific Units of Time

We want to find all employees hired in February or December, as well as employees hired on a Tuesday.

Comparing Records Using Specific Parts of a Date

We want to find which employees have been hired on the same month and weekday. For example, if an employee was hired on Monday, March 10, 2008, and another employee was hired on Monday, March 2, 2001, we want those two to come up as a match since the day of week and month match.

Identifying Overlapping Date Ranges

We want to find all instances of an employee starting a new project before ending an existing project.

Last updated