In my earlier article, I wrote a solution how to remove milliseconds from datetime. After that I tried to remove the seconds and milliseconds from datetime using same method but it gave me errors. So I went to the drawing board and started doing some research and finally realized that I can use the same methods with little modifications.
Given below are the two methods that we can use to remove milliseconds and seconds from datetime.
METHOD 1 :
In this method, we will use Convert function to convert date time to varchar and then remove the seconds and milliseconds from it and then convert it back to datetime.
Given below is the script.
--This script is compatible with SQL Server 2005 and above. DECLARE @datetime DATETIME SET @datetime = GETDATE() SELECT @datetime AS [Datetime with seconds and millisconds] ,CONVERT(DATETIME,CONVERT(VARCHAR(13),@datetime,120)+ ':00') AS [Datetime without seconds & millisconds] GO --OUTPUT
METHOD 2 :
In this method, we will first FORMAT the datetime value to a defined format (truncate seconds and milliseconds) and then convert it back to datetime data type using CAST function.
Given below is the script.
--This script is compatible with SQL Server 2012 and above. DECLARE @datetime DATETIME SET @datetime = GETDATE() SELECT @datetime AS [Datetime with seconds and millisconds] ,CAST(FORMAT(@datetime,'yyyy-MM-dd HH:0') AS datetime) AS [Datetime without seconds & millisconds] GO --OUTPUT