Date Functions

This section covers built-in date and time functions in SQL Server, which are essential for manipulating and calculating with date and time data types.

Overview

SQL Server provides a rich set of functions to work with dates and times. These functions allow you to extract specific parts of a date, calculate differences between dates, add or subtract intervals, convert between date formats, and much more. Understanding these functions is crucial for building robust and data-driven applications.

Common Date Functions

Examples

Getting Current Date and Time

To retrieve the current date and time:

SELECT GETDATE();
SELECT SYSDATETIME();

Extracting Date Parts

To get the year, month, and day from a specific date:

DECLARE @MyDate DATE = '2023-10-27';
SELECT
    YEAR(@MyDate) AS Year,
    MONTH(@MyDate) AS Month,
    DAY(@MyDate) AS Day,
    DATEPART(weekday, @MyDate) AS DayOfWeek;

Output might look like:

Year | Month | Day | DayOfWeek
-----|-------|-----|----------
2023 | 10    | 27  | 6

(Note: DayOfWeek can vary based on `DATEFIRST` setting.)

Adding or Subtracting Dates

To find the date one month from now, or 10 days ago:

SELECT DATEADD(month, 1, GETDATE()) AS OneMonthFromNow;
SELECT DATEADD(day, -10, GETDATE()) AS TenDaysAgo;

Calculating Date Differences

To find the number of days between two dates:

DECLARE @StartDate DATE = '2023-01-01';
DECLARE @EndDate DATE = '2023-10-27';
SELECT DATEDIFF(day, @StartDate, @EndDate) AS DaysDifference;

Formatting Dates

Using CONVERT for date formatting:

SELECT CONVERT(VARCHAR, GETDATE(), 103) AS FormattedDate_DDMMYYYY; -- DD/MM/YYYY
SELECT CONVERT(VARCHAR, GETDATE(), 101) AS FormattedDate_MMDDYYYY; -- MM/DD/YYYY
SELECT CONVERT(VARCHAR, GETDATE(), 120) AS FormattedDate_YYYYMMDD_HHMMSS; -- YYYY-MM-DD HH:MM:SS

Best Practices