SQL Date and Time Functions

SQL provides a rich set of functions to manipulate and extract information from date and time data types. These functions are essential for performing time-based analysis, scheduling, and managing temporal data.

Date and Time Functions Overview

The following are some of the most commonly used date and time functions available in SQL:

Getting Current Date and Time

Example:

SELECT GETDATE() AS CurrentDateTime;

Extracting Date Parts

These functions allow you to extract specific components (year, month, day, hour, etc.) from a date or time value.

Example:

SELECT
    YEAR('2023-10-27 10:30:00') AS YearPart,
    MONTH('2023-10-27 10:30:00') AS MonthPart,
    DAY('2023-10-27 10:30:00') AS DayPart;

Date Manipulation

These functions are used to add or subtract intervals from dates, or to calculate the difference between two dates.

Example:

SELECT
    DATEADD(day, 7, '2023-10-27') AS SevenDaysLater,
    DATEDIFF(month, '2023-01-01', '2023-10-27') AS MonthsDifference;

Formatting Dates

Convert dates and times into various string formats.

Example:

SELECT
    FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm:ss') AS FormattedDateTime,
    CONVERT(VARCHAR, GETDATE(), 103) AS FormattedDDMMYYYY;

Date Comparison and Validation

Other Function Categories