SQL provides a variety of date and time functions that allow you to manipulate and retrieve date-related information efficiently. These functions are useful for handling timestamps, date calculations, and formatting.

Common Date and Time Functions

Example Usage of Date and Time Functions

1. Using GETDATE() Function

SELECT GETDATE() AS CurrentDateTime;

Output. 2024-03-19 14:30:00.000 (Example output, actual output may vary)

2. Using DATEADD() Function

SELECT DATEADD(DAY, 7, '2024-03-19') AS NewDate; 

Output. 2024-03-26

3. Using DATEDIFF() Function

SELECT DATEDIFF(DAY, '2024-03-01', '2024-03-19') AS DaysDifference; 

Output.18

4. Using FORMAT() Function

SELECT Format(Getdate(), 'yyyy-MM-dd') AS FormattedDate;

SELECT Format(Getdate(), 'dd/MM/yyyy') AS FormattedDateDDMMYYYY;

SELECT Format(Getdate(), 'MMMM dd, yyyy') AS FormattedDateLong; 

Output

FormattedDate FormattedDateDDMMYYYY FormattedDateLong
2024-03-19 19/03/2024 March 19, 2024

5. Using EOMONTH() Function

SELECT EOMONTH(GETDATE()) AS EndOfMonth; 

Output. 2024-03-31

6. Using CONVERT() Function

SELECT CONVERT(VARCHAR, Getdate(), 101) AS MMDDYYYY;

SELECT CONVERT(VARCHAR, Getdate(), 103) AS DDMMYYYY;

SELECT CONVERT(VARCHAR, Getdate(), 120) AS YYYYMMDD_HHMMSS; 

Output

MMDDYYYY DDMMYYYY YYYYMMDD_HHMMSS
03/19/2024 19/03/2024 2024-03-19 14:30:00

7. Using CAST() Function

SELECT CAST(GETDATE() AS DATE) AS OnlyDate;

SELECT CAST(GETDATE() AS TIME) AS OnlyTime;

Output

OnlyDate OnlyTime
2024-03-19 14:30:00

When to Use Date and Time Functions?

Advantages of Date and Time Functions

Date and time functions are an essential part of SQL, providing efficient ways to handle date-related operations.