Microsoft SQL Server's date and time functions let you pull a date apart into its year, month and day parts, add or subtract intervals like days and months, work out the difference between two dates, and build a date from numbers. The quickest way in is to open SQL Server Management Studio (SSMS) or Azure Data Studio, connect to a database, and run a simple SELECT statement such as SELECT DATEPART(month, GETDATE()) to see how each function behaves. Everything below builds on that same pattern: call the function inside a SELECT, look at the result, then adapt it to your table.
What You'll Need
- A connection to a SQL Server database (SQL Server, Azure SQL Database, or Azure SQL Managed Instance), with permission to run queries.
- A client tool such as SQL Server Management Studio (SSMS) or Azure Data Studio. These steps use SSMS, but the SQL itself is the same in any client.
- A test database you are happy to experiment in. Avoid running update or delete statements on production data while learning.
- Basic comfort writing a SELECT statement and understanding column types.
Menu positions and wording in SSMS can differ slightly by version and by the server edition you connect to, so treat any button name below as a guide rather than a fixed label.
Step-by-Step
- Get the current date and time. Run
SELECT GETDATE(), SYSDATETIME(), CAST(GETDATE() AS date);. GETDATE returns the server's local date and time, SYSDATETIME returns higher precision, and the CAST strips the time so you have just a date. This single query tells you what time zone and precision you are working with, which matters before you start calculating. - Break a date into parts with DATEPART and DATENAME. Try
SELECT DATEPART(year, GETDATE()), DATEPART(month, GETDATE()), DATEPART(day, GETDATE()), DATENAME(month, GETDATE());. DATEPART returns a number (month 12, for instance), while DATENAME returns the name as text. Use DATEPART when you need to compare or group numbers, and DATENAME when the value is for display. - Extract single values quickly. The shorthand functions YEAR(), MONTH() and DAY() do the same job as DATEPART for those three parts. They are shorter and read well in WHERE clauses, for example
WHERE YEAR(OrderDate) = 2024. - Add or subtract time with DATEADD. The pattern is
DATEADD(interval, number, date). For example,SELECT DATEADD(day, 30, GETDATE())gives a date thirty days ahead, andDATEADD(month, -1, GETDATE())gives one month ago. Common intervals are year, quarter, month, day, week, hour, minute and second. Negative numbers subtract. - Find the gap between two dates with DATEDIFF.
DATEDIFF(interval, start, end)counts the number of interval boundaries crossed, not full periods.SELECT DATEDIFF(day, '2024-01-01', '2024-02-01')returns 31. Note that DATEDIFF counts the number of times the interval boundary is passed, so a day difference between late evening and early morning can still count as one. - Build a date from numbers with DATEFROMPARTS.
SELECT DATEFROMPARTS(2024, 12, 31)returns a real date value. This is useful when year, month and day sit in separate columns and you need them combined. Invalid combinations, such as month 13, raise an error rather than silently rolling over. - Format for display with FORMAT or CONVERT.
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')returns an ISO-style string. For older compatibility levels,CONVERT(varchar(10), GETDATE(), 23)produces the same shape. Keep the underlying value as a date and format only at the point of display. - Calculate month starts, month ends and weekdays. To get the first of the current month:
SELECT DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1). For the last day:SELECT EOMONTH(GETDATE()). For the day of the week:SELECT DATEPART(weekday, GETDATE()), remembering the numbering depends on the session's DATEFIRST setting, so set it explicitly if your queries rely on it. - Put it to work on a table. A typical reporting query groups orders by month:
SELECT DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) AS MonthStart, COUNT(*) FROM Orders GROUP BY DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1) ORDER BY MonthStart;. This gives one row per month with a real date you can chart. - Check results before using them in updates. When a date expression will drive an UPDATE or DELETE, run it first as a SELECT against the same filter. Confirm the row count and a few sample dates, then apply the change inside a transaction so you can roll back if the numbers are wrong.
Common Mistakes
Filtering with functions on an indexed column. Writing WHERE YEAR(OrderDate) = 2024 prevents SQL Server from using an index on OrderDate efficiently. Prefer a range: WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01'.
Assuming DATEDIFF counts full periods. DATEDIFF counts boundary crossings. Two dates 23 hours apart can return 1 for day. If you need exact elapsed time, use DATEDIFF_BIG with a smaller interval such as second or millisecond and convert.
Relying on implicit date formats. Strings like '03/04/2024' are ambiguous and can fail depending on language settings. Use unambiguous formats such as 'YYYY-MM-DD' or ISO 8601 with a T separator.
Mixing local and UTC times. GETDATE returns server local time. If your application stores UTC, compare against SYSUTCDATETIME or store UTC consistently, otherwise reports will be off by the offset.
Forgetting that DATEADD rolls over. Adding one month to January 31 gives February 28 or 29, not March 3, and this is intended behaviour, not an error. Plan month arithmetic with that in mind.
Tips
Use the date and time data types (date, datetime2, datetimeoffset) rather than datetime or varchar for new columns. They store more precisely and avoid string conversion problems.
Keep the interval keyword unquoted in DATEADD and DATEDIFF, for example DATEADD(day, 1, ...), not 'day'. Quoting still works in many cases but unquoted is the documented form and is less error-prone.
For time zone aware values, use datetimeoffset and switch with SWITCHOFFSET or AT TIME ZONE rather than manually adding hours, since daylight saving changes will otherwise catch you out.
Comment the intent of date logic in reporting queries. A reader six months later will not know whether a boundary is inclusive or exclusive unless you say so.
Troubleshooting
An error says the conversion failed when converting date or time from a character string. The string is in a format the server does not recognise, or the language setting differs. Rewrite the literal as 'YYYY-MM-DD' and rerun.
DATEFROMPARTS gives an error. One of the parts is out of range or NULL. Check the columns feeding it for month 0, day 32, or missing values, and handle NULLs with ISNULL or a CASE expression.
Results look a day out. Check the server's time zone, whether the column is datetimeoffset, and whether DATEFIRST or language settings differ between your session and the app. Test with a fixed known date to isolate the cause.
FORMAT is slow on large result sets. FORMAT is convenient but can be slower than CONVERT. For big reports, format in the presentation layer or use CONVERT with a style code.
A query that worked yesterday now returns nothing. Confirm the server clock and time zone, then check whether the data actually falls in the range you assumed. Select the raw dates for a handful of rows before trusting the aggregate.
Frequently Asked Questions
What is the difference between GETDATE and SYSDATETIME?
GETDATE returns datetime with roughly millisecond precision; SYSDATETIME returns datetime2 with much finer precision. Both reflect the server's local time. Use SYSDATETIME when you need greater accuracy.
How do I get the first day of the month in SQL Server?
Use DATEFROMPARTS(YEAR(date), MONTH(date), 1), or EOMONTH(date, -1) plus one day. EOMONTH(date) gives the last day of the month containing that date.
Why does DATEDIFF give an unexpected number?
Because it counts interval boundaries, not complete periods. Two timestamps that are hours apart can differ by one day. Use a finer interval if you need precise elapsed time.
Can I store dates as text?
You can, but avoid it for anything you will sort, compare or calculate on. Native date types are faster, validate input, and avoid format ambiguity.
What does EOMONTH handle better than manual arithmetic?
It handles leap years and varying month lengths for you, returning the correct last day without extra logic. Its optional second argument shifts the month forward or back.
Do these functions work in Azure SQL Database and Managed Instance?
Yes, the core date functions shown here are available in Azure SQL Database, Azure SQL Managed Instance and SQL Server. A few newer functions depend on the database compatibility level, so check that if a function is reported as unknown.