SQL Server date functions allow you to capture the current system time, manipulate date values, calculate the difference between two timestamps, and format dates for reporting. To use these functions, you need a database environment running Microsoft SQL Server and a query editor such as SQL Server Management Studio (SSMS) or Azure Data Studio.
What You'll Need
- Access to a SQL Server instance (Local, Network, or Azure SQL Database).
- A query tool like SQL Server Management Studio (SSMS).
- A table containing date or datetime columns, or the ability to run ad-hoc SELECT statements for testing.
Step-by-Step
- Retrieve the Current System Date and Time
The first step in working with dates is knowing how to capture the current moment. UseGETDATE()to return the current system timestamp of the computer on which the instance of SQL Server is running. For higher precision, useSYSDATETIME(), which returns adatetime2(7)value.SELECT GETDATE() AS CurrentDateTime, SYSDATETIME() AS PreciseDateTime; - Extract Specific Parts of a Date
Often, you do not need the full timestamp but only a specific component, such as the year or the month. Use theDATEPART()function or the specialized shorthand functions.DATEPART(year, '2023-12-25')returns 2023.
Alternatively, use these specific functions for cleaner code:YEAR(date): Returns the year integer.MONTH(date): Returns the month (1-12).DAY(date): Returns the day of the month.
- Add or Subtract Time Intervals
To calculate future or past dates (such as an expiration date 30 days from now), useDATEADD(). This function requires three arguments: the date part to add, the number to add, and the starting date.SELECT DATEADD(day, 30, GETDATE()) AS ExpirationDate;
To subtract time, simply use a negative number:DATEADD(month, -1, GETDATE())will return the date from exactly one month ago. - Calculate the Difference Between Two Dates
To find the elapsed time between two timestamps, useDATEDIFF(). This function calculates the count of the specified datepart boundaries crossed between the start date and the end date.SELECT DATEDIFF(day, '2023-01-01', '2023-01-10') AS DaysDiff;
This returns 9. Be aware thatDATEDIFFcounts boundaries; if you compare 11:59 PM on Monday to 12:01 AM on Tuesday usingday, the result is 1, even though only two minutes have passed. - Format Dates as Strings
For reporting, you often need dates in a specific format (e.g., MM/DD/YYYY). Use theFORMAT()function for flexibility orCONVERT()for performance.SELECT FORMAT(GETDATE(), 'dd-MM-yyyy') AS FormattedDate;
WhileFORMAT()is intuitive (using .NET formatting strings),CONVERT()is significantly faster for large datasets. For example,CONVERT(varchar, GETDATE(), 101)produces the US standard mm/dd/yyyy. - Handle Date Truncation and Casting
If you have adatetimevalue but only want the date portion (removing the time), the most efficient method in modern SQL Server versions is to cast the value to theDATEdata type.SELECT CAST(GETDATE() AS DATE) AS DateOnly;
This is preferable to usingCONVERTto a string and back to a date, as it preserves the data type and improves query performance.
Common Mistakes
One of the most frequent errors is confusing DATEDIFF with a precise duration calculation. Because DATEDIFF counts the number of boundaries crossed, it can lead to "off-by-one" errors in business logic. For example, DATEDIFF(year, '2023-12-31', '2024-01-01') returns 1, despite only one day having passed.
Another common mistake is using the FORMAT() function in the WHERE clause of a query. FORMAT() is computationally expensive. Applying it to a column in a large table prevents the SQL Server optimizer from using indexes (this is known as making the query non-SARGable), which can turn a millisecond query into one that takes several minutes.
Users also frequently confuse GETDATE() with CURRENT_TIMESTAMP. While they return the same value, GETDATE() is a T-SQL function and requires parentheses, whereas CURRENT_TIMESTAMP is an ANSI SQL standard constant and does not use parentheses.
Tips
To optimize performance when filtering by date, always keep the column "naked." Instead of using WHERE YEAR(OrderDate) = 2023, use a range: WHERE OrderDate >= '2023-01-01' AND OrderDate < '2024-01-01'. This allows SQL Server to utilize indexes on the OrderDate column.
When dealing with global applications, avoid GETDATE() and use GETUTCDATE(). Storing all timestamps in Coordinated Universal Time (UTC) prevents massive headaches related to Daylight Savings Time (DST) transitions and allows you to easily convert the time to a user's local timezone using AT TIME ZONE.
For complex date logic, such as finding the last day of the current month, use EOMONTH(). This built-in function is much simpler than the old method of adding one month and subtracting the day of the month.
Troubleshooting
Error: "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
This usually happens because of regional date format settings (e.g., interpreting MM/DD/YYYY as DD/MM/YYYY). To fix this, always use the ISO 8601 standard format 'YYYY-MM-DD' or 'YYYYMMDD', which are language-neutral and interpreted consistently regardless of server settings.
Issue: The date is returning as 1900-01-01.
In SQL Server, the integer 0 is treated as the base date of January 1, 1900. If you see this date, it usually means you are performing a calculation that resulted in 0 or you are casting a null/zero value into a date type.
Issue: Query is running extremely slowly on date filters.
Check if you are using functions like LEFT(), SUBSTRING(), or FORMAT() on your date column in the WHERE clause. If so, remove the function and use a date range comparison (>= and <) to restore index usage.
Frequently Asked Questions
What is the difference between DATETIME and DATETIME2?
DATETIME2 has a larger date range, higher precision (up to 7 decimal places for seconds), and is more compliant with the SQL standard than the older DATETIME type.
How do I find the number of working days between two dates?
SQL Server does not have a built-in NETWORKDAYS function. You must either create a Calendar Table containing all dates and a boolean IsWorkDay column, or use a WHILE loop or Common Table Expression (CTE) to count days while excluding Saturdays and Sundays.
Can I change the date format globally for the whole server?
You can change the LANGUAGE or DATEFORMAT settings for a session, but it is highly discouraged. It is better to explicitly format dates in your SELECT statement or handle formatting in the application's front-end code.
How do I add 6 months to a date?
Use DATEADD(month, 6, YourDateColumn). This function automatically handles the transition to the next year.
What does EOMONTH do?
EOMONTH() returns the last day of the month for the specified date. You can also provide an optional second argument to find the end of the month for a date offset by a certain number of months.