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
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.
A faster way would be to work with the Ticks property: DateTime dtNew = dt. AddTicks(-(dt. Ticks % 10000000));
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.
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
The fastest, also language safe and deterministic
DATEADD(second, DATEDIFF(second, '20000101', getdate()), '20000101')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With