October 15, 2010

Truncate Hour, Minute, Second and MilliSecond in SQL Server

Here’s how to Truncate a DateTime in SQL Server

SELECT GETDATE() as CurrentDateTime;
SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),0) as [Truncate-HrMinSecMilliSec];
SELECT DATEADD(hour,DATEDIFF(hour,0,GETDATE()),0) as [Truncate-MinSecMilliSec];
SELECT DATEADD(minute,DATEDIFF(minute,0,GETDATE()),0) as [Truncate-SecMilliSec];

Now when I did the same for seconds using

SELECT DATEADD(second,DATEDIFF(second,0,GETDATE()),0);

I got the error

Msg 535, Level 16, State 0, Line 1

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.


To resolve the error, do the following:

SELECT DATEADD(second,DATEDIFF(second, '2010-10-01',GETDATE()),'2010-10-01') as [Truncate-MilliSec];

Here’s the Output after running all the queries

image


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

2 comments:

Dan said...

How about

SELECT CONVERT(datetime, FLOOR(CONVERT(float, GETDATE())))

Suprotim Agarwal said...

Dan yes that's an alternative and it's called the CAST-FLOOR-CAST method. But I saw a slight performance improvement while using DATEADD-DATEDIFF over C-F-C.