Truncate Datetime to Second (Remove Milliseconds)

2019-01-09 02:24发布

What is the best way to shorten a datetime that includes milliseconds to only have the second?

For example 2012-01-25 17:24:05.784 to 2012-01-25 17:24:05

标签: tsql datetime
5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-09 02:46

This will truncate the milliseconds.

declare @X datetime
set @X = '2012-01-25 17:24:05.784'
select convert(datetime, convert(char(19), @X, 126))

or

select dateadd(millisecond, -datepart(millisecond, @X), @X)

CAST and CONVERT
DATEADD
DATEPART

查看更多
放我归山
3楼-- · 2019-01-09 02:53
convert(datetime, convert(varchar, @datetime_var, 120), 120)
查看更多
叛逆
4楼-- · 2019-01-09 02:57

The following has very fast performance, but it not only removes millisecond but also rounds to minute. See (http://msdn.microsoft.com/en-us/library/bb677243.aspx)

select cast(yourdate as smalldatetime) from yourtable

Edit:

The following script is made to compare the scripts from Mikael and gbn I upvoted them both since both answers are great. The test will show that gbn' script is slightly faster than Mikaels:

declare @a datetime
declare @x int = 1 
declare @mikaelend datetime

declare @mikael datetime = getdate() 
while @x < 5000000 
begin   
  select @a = dateadd(millisecond, -datepart(millisecond, getdate()), getdate()) , @x +=1 
end  
set @mikaelend = getdate()

set @x = 1 
declare @gbnend datetime
declare @gbn datetime = getdate() 
while @x < 5000000
begin 
  select @a = DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')  , @x +=1 
end  
set @gbnend = getdate()
select datediff(ms, @mikael, @mikaelend) mikael, datediff(ms, @gbn, @gbnend) gbn 

First run

mikael      gbn
----------- -----------
5320        4686

Second run

mikael      gbn
----------- -----------
5286        4883

Third run

mikael      gbn
----------- -----------
5346        4620
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-09 02:58

so, the easiest way now is:

select convert(datetime2(0) , getdate())

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-09 03:07

The fastest, also language safe and deterministic

DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')
查看更多
登录 后发表回答