Explore various date and time functions and examples in SQL Server.
SQL Server offers several data types for storing date and time information. Some of the most commonly used types include:
DATE
: Stores a date (year, month, day).DATETIME
: Stores a date and time.DATETIME2
: Stores a date and time with higher precision.SMALLDATETIME
: Stores a date and time with lower precision.You can perform arithmetic operations on date and time values.
-- Add 1 day to a date
SELECT DATEADD(day, 1, GETDATE());
-- Subtract 2 weeks from a datetime value
SELECT DATEADD(week, -2, GETDATE());
-- Calculate the difference between two dates
SELECT DATEDIFF(day, '2023-10-26', '2023-10-27');
You can format date and time values to display them in different formats.
-- Format a datetime value
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm:ss');