SQL Server Date and Time Samples

Explore various date and time functions and examples in SQL Server.

Date and Time Data Types

SQL Server offers several data types for storing date and time information. Some of the most commonly used types include:

Date Arithmetic

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');
                
            

Formatting Date and Time Values

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');