Monday, 25 August 2014

SQL Server - Remove or Truncate or Subtract hours, minutes, seconds and milliseconds from sql datetime


While working on SQL Datetime sometimes we may get a requirement to subtract hours, minutes, seconds and milliseconds from sql datetime. We can do it by using the following code snippet.

Remove/Truncate/Subtract hours, minutes, seconds and milliseconds from sql datetime

SELECT GETDATE()
-- 2014-08-25 13:19:13.157

SELECT CONVERT(DATETIME,CONVERT(char(10), GetDate(), 120))
-- 2014-08-25 00:00:00.000

SELECT
          DATEADD(MILLISECOND,(0-DATEPART(MILLISECOND,GETDATE())),
          DATEADD(SECOND,(0-DATEPART(SECOND,GETDATE())),
          DATEADD(MINUTE,(0-DATEPART(MINUTE,GETDATE())),
          (DATEADD(HOUR,(0-DATEPART(HOUR,GETDATE())),GETDATE())))))
-- 2014-08-25 00:00:00.000

No comments: