30

How do i trunc the date in sql server 2008 like this :

I have 2012-01-02 12:04:11.443 and I want only to select 2012-01-02 12:00:00.000 and 2012-01-02 12:04:00.000 (hour and minute level)

abatishchev
  • 95,331
  • 80
  • 293
  • 426
pufos
  • 2,782
  • 7
  • 33
  • 37
  • possible duplicate of [How can I truncate a datetime in SQL Server?](http://stackoverflow.com/questions/923295/how-can-i-truncate-a-datetime-in-sql-server) – Justin Cave Mar 20 '12 at 08:58
  • In particular, see BG100's answer in that thread. – Justin Cave Mar 20 '12 at 08:59
  • possible duplicate of [T-SQL datetime rounded to nearest minute and nearest hours with using functions](http://stackoverflow.com/questions/6666866/t-sql-datetime-rounded-to-nearest-minute-and-nearest-hours-with-using-functions) – user272735 Jan 13 '15 at 18:42

3 Answers3

59
declare @D as datetime = '2012-01-02T12:04:11.443'

select dateadd(hour, datediff(hour, 0, @D), 0)
select dateadd(minute, datediff(minute, 0, @D), 0)
Mikael Eriksson
  • 132,594
  • 21
  • 199
  • 273
5

This seems to work:

select [Rounded Time] =
    dateadd(mi,datediff(mi,0,dateadd(ss,30,a.DT)),0)

from
    (
    select dt = convert(datetime,'8:24:29.997')
    union all
    select dt = convert(datetime,'8:24:30.000')
    ) a

Results:

Rounded Time                                           
------------------------------------------------------ 
1900-01-01 08:24:00.000
1900-01-01 08:25:00.000

(2 row(s) affected)
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
SmartestVEGA
  • 7,601
  • 21
  • 79
  • 127
  • If you post code, XML or data samples, **PLEASE** highlight those lines in the text editor and click on the "code samples" button ( `{ }` ) on the editor toolbar to nicely format and syntax highlight it! – marc_s Mar 20 '12 at 09:01
  • thank you for answer .. Mikael Eriksson has a more simple answer. Also + 1 for the answer. Thanks – pufos Mar 20 '12 at 09:29
0

I'm using something like this:

DATEADD(hour,DATEDIFF(hour,'2000-01-01 00:00',[timestamp]),'2000-01-01 00:00')

You can use this formula to truncate to other levels, ie minutes:

DATEADD(minutes,DATEDIFF(minutes,'2000-01-01 00:00',[timestamp]),'2000-01-01 00:00')

You must remember that if you are truncating to seconds level, the maximum difference between the base date and [timestamp] is 68 years.

maniek765
  • 27
  • 5