Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate Datetime to Second (Remove Milliseconds) in T-SQL

Tags:

datetime

tsql

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

like image 550
Kyle Brandt Avatar asked Jan 26 '12 13:01

Kyle Brandt


People also ask

How can remove seconds and milliseconds from datetime in SQL?

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.

How do I remove datetime from milliseconds?

A faster way would be to work with the Ticks property: DateTime dtNew = dt. AddTicks(-(dt. Ticks % 10000000));

How do I truncate a timestamp from a date in SQL Server?

The TRUNC (date) function returns date with the time portion of the day truncated to the unit specified by the format model fmt . The value returned is always of datatype DATE , even if you specify a different datetime datatype for date . If you omit fmt , then date is truncated to the nearest day.


2 Answers

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

like image 101
Mikael Eriksson Avatar answered Oct 11 '22 12:10

Mikael Eriksson


The fastest, also language safe and deterministic

DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101') 
like image 38
gbn Avatar answered Oct 11 '22 12:10

gbn