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


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


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook


Dan said...

How about


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.