Extract and Filter Date Parts in SQL Server
SQL Server offers different operations for different date tasks. DATEPART returns an integer such as the year or minute. A cast to date removes the time component from a value, while DATETRUNC returns the beginning of a larger time unit. Use a range predicate when selecting rows that fall within a period.
Run each code example below as a separate batch. The examples deliberately declare their own input variables.
Extract Numeric Components
DECLARE @RecordedAt datetime2(0) = '2026-04-15T13:42:09';
SELECT DATEPART(year, @RecordedAt) AS YearNumber,
DATEPART(quarter, @RecordedAt) AS QuarterNumber,
DATEPART(month, @RecordedAt) AS MonthNumber,
DATEPART(minute, @RecordedAt) AS MinuteNumber;
The result is 2026, 2, 4 and 42. The datepart names are keywords, not quoted strings. Prefer the full names over ambiguous abbreviations such as m, which means month rather than minute.
Return a Date or a Period Boundary
DECLARE @RecordedAt datetime2(0) = '2026-04-15T13:42:09';
SELECT CAST(@RecordedAt AS date) AS DateOnly,
CAST(@RecordedAt AS time(0)) AS TimeOnly,
DATETRUNC(month, @RecordedAt) AS MonthStart;
Expect 2026-04-15, 13:42:09 and the start of April at midnight. DATETRUNC requires SQL Server 2022 or later. These values remain typed dates/times rather than formatted display strings.
Filter a Whole Day with a Half-Open Range
DECLARE @Start datetime2(0) = '2026-04-15T00:00:00';
DECLARE @End datetime2(0) = '2026-04-16T00:00:00';
SELECT EventId, RecordedAt
FROM (VALUES
(1, CAST('2026-04-15T23:59:59' AS datetime2(0))),
(2, CAST('2026-04-16T00:00:00' AS datetime2(0)))
) AS e(EventId, RecordedAt)
WHERE RecordedAt >= @Start AND RecordedAt < @End;
Only event 1 is returned. The inclusive start and exclusive end avoid guessing the final representable fraction of a second. On a real indexed column, this also avoids wrapping every stored value in DATEPART merely to test a period.
Define Calendar and Time-Zone Rules
Week and weekday calculations can depend on SET DATEFIRST. ISO-week numbering has its own boundary rules, so pairing an ISO week with a calendar year can be misleading around New Year. Specify the reporting convention deliberately.
datetime2 does not carry a time zone. If the stored values are UTC and the report uses a local day, compute the corresponding UTC boundaries with the intended time-zone rules before filtering. Extracting the local-looking date from a UTC timestamp does not perform that conversion.
Microsoft References
Author: Herman Schoenfeld