John Gietzen
John Gietzen

Reputation: 49544

What is the best way to truncate a date in SQL Server?

If I have a date value like 2010-03-01 17:34:12.018

What is the most efficient way to turn this into 2010-03-01 00:00:00.000?

As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?

Upvotes: 24

Views: 88098

Answers (7)

Ed Gibbs
Ed Gibbs

Reputation: 26353

SQL Server 2022 introduces the DATETRUNC() function, which is similar to the long-available Oracle TRUNC() function. It's also available in Azure SQL.

Syntax: DATETRUNC(datepart, date)

SELECT
  1 AS SortKey,
  '(none)' AS [Trunc date part],
  'Right now' AS Result,
  SYSDATETIME() AS Value
UNION SELECT 2, 'YEAR', 'Beginning of this year', DATETRUNC(YEAR, SYSDATETIME())
UNION SELECT 3, 'MONTH', 'Beginning of this month', DATETRUNC(MONTH, SYSDATETIME())
UNION SELECT 4, 'DAY', 'Zero hour today', DATETRUNC(DAY, SYSDATETIME())
UNION SELECT 5, 'HOUR', 'Beginning of this hour', DATETRUNC(HOUR, SYSDATETIME())
UNION SELECT 6, 'MINUTE', 'Beginning of this minute', DATETRUNC(MINUTE, SYSDATETIME())
UNION SELECT 7, 'SECOND', 'Beginning of this second', DATETRUNC(SECOND, SYSDATETIME())
ORDER BY SortKey

Results from running at around 11:30 PM on 16 June 2023:

SortKey Trunc date part Result Value
1 (none) Right now 2023-06-17 03:30:04.4097820
2 YEAR Beginning of this year 2023-01-01 00:00:00.0000000
3 MONTH Beginning of this month 2023-06-01 00:00:00.0000000
4 DAY Zero hour today 2023-06-17 00:00:00.0000000
5 HOUR Beginning of this hour 2023-06-17 03:00:00.0000000
6 MINUTE Beginning of this minute 2023-06-17 03:30:00.0000000
7 SECOND Beginning of this second 2023-06-17 03:30:04.0000000

Fiddle

Upvotes: 2

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171491

If you are using SQL Server 2008+, you can use the Date datatype like this:

select cast(getdate() as date)

If you still need your value to be a DateTime datatype, you can do this:

select cast(cast(getdate() as date) as datetime)

A method that should work on all versions of SQL Server is:

select cast(floor(cast(getdate() as float)) as datetime)

Upvotes: 19

Caius Jard
Caius Jard

Reputation: 74660

If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:

--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)

Breaking this down:

  • DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"

  • ( ... -7)%7 - we subtract 7 from it and modulo the result by 7.

    • We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
    • This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
    • This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
    • If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
    • This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
  • DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step

If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc

Upvotes: 0

Brett Seiler
Brett Seiler

Reputation: 1

Not sure if this is the most efficient, but I like the simplicity in using the following where @SomeDate is your field.

Concat(Year(@SomeDate), '-', Month(@SomeDate), '-', '01')

Upvotes: 0

Andrew
Andrew

Reputation: 373

This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.

declare @SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT 
 DATEFROMPARTS(
     YEAR(@SomeDate)
    ,MONTH(@SomeDate)
    ,'01'
    ) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
     YEAR(@SomeDate)                     
    ,MONTH(@SomeDate)                
    ,'01' --DAY(@SomeDate)                   
    ,'00' --DATEPART(HOUR,@SomeDate)         
    ,'00' --DATEPART(MINUTE,@SomeDate)       
    ,'00' --DATEPART(SECOND,@SomeDate)       
    ,'00' --DATEPART(MILLISECOND,@SomeDate) 
    ) AS CUR_DATETIME_FROM_PARTS
,@SomeDate                         AS CUR_DATETIME
,YEAR(@SomeDate)                   AS CUR_YEAR
,MONTH(@SomeDate)                  AS CUR_MONTH
,DAY(@SomeDate)                    AS CUR_DAY
,DATEPART(HOUR,@SomeDate)          AS CUR_HOUR
,DATEPART(MINUTE,@SomeDate)        AS CUR_MINUTE
,DATEPART(SECOND,@SomeDate)        AS CUR_SECOND
,DATEPART(MILLISECOND,@SomeDate)   AS CUR_MILLISECOND
FROM Your_Table

Truncated Date: 2010-03-01

Truncated DateTime: 2010-03-01 00:00:00.000

DateTime: 2010-03-01 17:34:12.017

Upvotes: 3

Andomar
Andomar

Reputation: 238176

To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;

select dateadd(d, 0, datediff(d, 0, getdate()))

The second method is text based: it truncates the text description with varchar(10), leaving only the date part:

select convert(varchar(10),getdate(),111)

The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:

select cast(floor(cast(getdate() as float)) as datetime)

To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:

select dateadd(dd, 1 - datepart(dw, getdate()), getdate())

This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with @start_of_day as a variable for readability:

declare @start_of_day datetime
set @start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, @start_of_day), @start_of_day)

The start of the year, month, hour and minute still work with the "difference since 1900" approach:

select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)

Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:

declare @start_of_day datetime
set @start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, @start_of_day, getdate()), @start_of_day)

To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:

select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)

This works for quarters and half hours as well.

Upvotes: 39

Oleks
Oleks

Reputation: 32343

Try:

SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)

UPDATE: answer on the second question: for years you could use a little bit modified version of my answer:

SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)

for quarter:

SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)

and so on.

I checked, up to minutes - it's OK. But on seconds I've got an overflow message:

Difference of two datetime columns caused overflow at runtime.

One more update: take a look to the following answer to the same question

Upvotes: 3

Related Questions