DateTime is one of the most crucial data types used in the database. It can be used to track events, manage schedules, and analyze trends. If you are not properly handling datetime values, it can lead to errors, inaccurate reports, and even business losses. Developers often encounter challenges like formatting inconsistencies, handling NULLs, and managing time zones.
If you master the DateTime functions, you can simplify your queries, reduce bugs, and ensure your data is accurate and actionable. This blog will cover all the DateTime functions with examples and actionable tips.
SQL Server DateTime Functions
SQL Server provides a variety of DateTime functions categorized into the following groups:
1. Current Date and Time Retrieval
These functions return the current system date and/or time.
GETDATE()
Returns the current date and time from the system.
SELECT GETDATE() AS CurrentDateTime;
-- Output
-- 2024-12-26 21:52:10.887
SYSDATETIME()
Returns the current date and time more precisely (including fractional seconds).
SELECT SYSDATETIME() AS CurrentDateTimeWithPrecision;
-- Output
-- 2024-12-26 21:53:31.5463103
CURRENT_TIMESTAMP
Returns the current date and time as a datetime. Equivalent to GETDATE()
SELECT CURRENT_TIMESTAMP AS CurrentDateTime;
-- Output
-- 2024-12-26 21:54:36.653
SYSUTCDATETIME()
Returns the current date and time in UTC format.
SELECT SYSUTCDATETIME() AS CurrentDateTimeUTC;
-- Output
-- 2024-12-26 16:25:31.2487144
2. Date and Time Parts
Functions to extract specific parts of a DateTime value.
YEAR()
Returns the year part of a date.
SELECT YEAR(GETDATE()) AS CurrentYear;
-- Output
-- 2024
MONTH()
Returns the month part of a date.
SELECT MONTH(GETDATE()) AS CurrentMonth;
-- Output
-- 12
DAY()
Returns the day of the month.
SELECT DAY(GETDATE()) AS CurrentDay;
-- Output
-- 26
DATENAME()
Returns the name of the specified part of a date.
SELECT DATENAME(MONTH, GETDATE()) AS CurrentMonthName;
-- Output
-- December
DATEPART()
Returns an integer representing the specified part of a date.
SELECT DATEPART(WEEKDAY, GETDATE()) AS DayOfWeek;
-- Output
-- 5
You can check different date parts from here.
3. Date and Time Manipulation
Functions to modify date and time values.
DATEADD()
Adds a specified number to a part of the date.
SELECT DATEADD(DAY, 20, GETDATE()) AS DateAfter20Days
-- Output
-- 2025-01-16 14:59:30.573
DATEDIFF()
Returns the difference between two dates for a specific part.
SELECT DATEDIFF(DAY, '2024-11-01', GETDATE()) AS DaysDifference;
-- Output
-- 56
EOMONTH()
Returns the last day of the month for a specified date.
SELECT EOMONTH(GETDATE()) AS EndOfMonth;
-- Output
-- 2024-12-31
4. Date and Time Formatting
Functions to format DateTime values.
CONVERT()
Converts a date to a specific format.
SELECT CONVERT(VARCHAR, GETDATE(), 101) AS FormattedDate; -- MM/DD/YYYY
-- Output
-- 12/27/2024
You can check all other formats like 102,103 etc. from here.
FORMAT()
Customizes date and time formatting.
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS FormattedDate
-- Output
-- 2024-12-27
5. Date and Time Comparison
ISDATE()
Check if a value is a valid date.
SELECT ISDATE('2024-12-25') AS IsValidDate;
-- Output
-- 1
SELECT ISDATE('dotnetinfinity') AS IsValidDate;
-- Output
-- 0
6. Miscellaneous Functions
GETUTCDATE()
Returns the current UTC date and time.
SELECT GETUTCDATE() AS UTCDateTime;
-- Output
-- 2024-12-27 13:16:48.477
SWITCHOFFSET()
Adjusts a datetimeoffset value to a new time zone.
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-08:00') AS AdjustedTimeZone;
-- Output
-- 2024-12-27 05:17:18.1047923 -08:00
TODATETIMEOFFSET()
Converts a datetime to a datetimeoffset with a specified time zone.
SELECT TODATETIMEOFFSET(GETDATE(), '+05:30') AS DateTimeWithOffset;
-- Output
-- 2024-12-27 15:17:57.953 +05:30
TRY_CAST(), TRY_CONVERT()
Converts a value to datetime safely (returns NULL if conversion fails).
SELECT TRY_CAST('2024-12-25' AS DATETIME) AS SafeConversion;
-- Output
-- 2024-12-25 00:00:00.000
SELECT TRY_CAST('dotnetinfinity' AS DATETIME) AS SafeConversion;
-- Output
-- NULL
SELECT TRY_CONVERT(DATETIME, '2024-12-25') AS ConvertedDateTime;
-- Output
-- 2024-12-25 00:00:00.000
SELECT TRY_CONVERT(DATETIME, 'dotnetinfinity') AS ConvertedDateTime;
-- Output
-- NULL
7. New Functions (SQL Server 2012 and Later)
DATEFROMPARTS()
Returns a date from individual parts (year, month, day).
SELECT DATEFROMPARTS(2024, 12, 31) AS ConstructedDate;
-- Output
-- 2024-12-31
TIMEFROMPARTS()
Returns a time from individual parts.
SELECT TIMEFROMPARTS(10, 30, 00, 0, 0) AS ConstructedTime;
-- Output
-- 10:30:00
DATETIMEFROMPARTS()
Returns a datetime from individual parts.
SELECT DATETIMEFROMPARTS(2024, 12, 31, 10, 30, 00, 0) AS ConstructedDateTime;
-- Output
-- 2024-12-31 10:30:00.000
DATETIME2FROMPARTS()
Returns a datetime2 value from parts.
SELECT DATETIME2FROMPARTS(2024, 12, 31, 10, 30, 00, 0, 7) AS ConstructedDateTime2;
-- Output
-- 2024-12-31 10:30:00.0000000
Let’s understand some real-world Scenarios
Scenario 1: Generating Sales Reports
You need to generate daily, monthly, and yearly sales reports.
SELECT FORMAT(OrderDate, 'yyyy-MM') AS OrderMonth, COUNT(*) AS TotalOrders
FROM Orders
GROUP BY FORMAT(OrderDate, 'yyyy-MM');
Scenario 2: Calculating Delivery Time
Calculate the time difference between order placement and delivery.
SELECT OrderID, DATEDIFF(DAY, OrderDate, DeliveryDate) AS DeliveryTimeInDays
FROM Orders;
Scenario 3: Formatting Dates for Exports
Format dates for exporting to Excel.
SELECT CONVERT(VARCHAR, GETDATE(), 103) AS ExportDate;
Advanced Tips and Best Practices
Performance Considerations
Avoid using functions on columns in WHERE clauses, as this can prevent index usage.
Understanding Data Types
- DATETIME: Supports fractional seconds but less precise than DATETIME2.
- DATETIME2: Preferred for new applications due to better precision.
- DATE: Use when you only need the date without time.
Handling Time Zones
Use AT TIME ZONE to manage time zones in global applications.
SELECT SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' AS PSTTime;
Dealing with NULLs
Always handle NULLs to prevent runtime errors.
SELECT ISNULL(OrderDate, '1900-01-01') AS SafeOrderDate FROM Orders;
Conclusion
Mastering SQL Server DateTime functions is essential for efficient data handling and accurate reporting. You can avoid costly mistakes and optimise your workflows by understanding how to retrieve, manipulate, format, and compare datetime values. Start applying these functions today to see immediate improvements in your SQL Server projects.