Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate date to only hour / minute

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)

like image 212
pufos Avatar asked Mar 20 '12 08:03

pufos


People also ask

How do I truncate a date and time in SQL?

SQL Server SPID – What is it? » In Oracle there is a function (trunc) used to remove the time portion of a date. In order to do this with SQL Server, you need to use the convert function. Convert takes 3 parameters, the datatype to convert to, the value to convert, and an optional parameter for the formatting style.

How do I get only hours and minutes from datetime in SQL?

We can use DATEPART() function to get the HOUR part of the DateTime in Sql Server, here we need to specify datepart parameter of the DATEPART function as hour or hh.

How do I trunc a timestamp?

If you want to TRUNC to the second, there are a few ways to do that. A couple of the simplest are using Date addition of 0 which will implicitly convert TIMESTAMP to a DATE, dropping the fractional seconds and then add 0 which, obviously, doesn't change the value. Then CAST that result back to a TIMESTAMP.


3 Answers

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)
like image 51
Mikael Eriksson Avatar answered Oct 09 '22 00:10

Mikael Eriksson


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)
like image 28
SmartestVEGA Avatar answered Oct 09 '22 00:10

SmartestVEGA


As of SQL Server 2022 CTP 2.1, there is a native function in SQL to do this called DATETRUNC(). You can pick the date/time level to which you would like to truncate the date. Documentation is here.

DATETRUNC(hour, YourDate)
like image 38
Conor Cunningham MSFT Avatar answered Oct 08 '22 23:10

Conor Cunningham MSFT