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
Thank you.. Imran. Its really useful.
I am adding one more method to get time stamp without seconds and milli seconds.
–This script is compatible with SQL Server 2008 and above.
DECLARE @datetime DATETIME
SET @datetime = GETDATE()
SELECT
@datetime AS [Datetime with seconds and millisconds]
,cast(CAST(@datetime as date) as varchar(11))+’ ‘+cast(DATEPART(HH,@datetime) as char(2))+’:00:00:000′
AS [Datetime without seconds & millisconds]
GO
–OUTPUT
Datetime with seconds and millisconds Datetime without seconds & millisconds
————————————- ————————————–
2013-09-20 10:35:54.140 2013-09-20 10:00:00:000
Thanks Durga, Good one.
is this script to remove minutes as well? because the minute part seems got stripped away as well.
Yes the first script converts minutes to zeroes, too. In that example, change VARCHAR(13) to VARCHAR(16) if you want to keep the minutes value intact.
Awesome solution! Thanks a lot!