Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i need date difference mill second

select DATEADD(Day, DATEDIFF(Day, 0, getdate()) - 1, -0.0000001)

2018-07-23 23:59:59.993

but i need as 2018-07-23 23:59:59.999

What I have tried:

I have tried as added zero

select DATEADD(Day, DATEDIFF(Day, 0, getdate()) - 1, -0.00000001)

2018-07-24 00:00:00.000

but i excepted as

2018-07-23 23:59:59.999
Posted
Updated 25-Jul-18 4:16am

Assuming SQL 2008 or higher, you'll need to use the new datetime2(7) type[^].
SQL
SELECT DateAdd(millisecond, -1, Cast(DateAdd(day, -1, Cast(SysDateTime() As date)) As datetime2(7)));
-- Output: 2018-07-23 23:59:59.9990000

Breaking that down:
SQL
DECLARE @Now datetime2(7) = SysDateTime();                                   -- Get the current date and time
DECLARE @Today date = Cast(@Now As date);                                    -- Remove the time part
DECLARE @Yesterday date = DateAdd(day, -1, @Today);                          -- Subtract one day
DECLARE @YesterdayDateTime datetime2(7) = Cast(@Yesterday As datetime2(7));  -- Need a datetime2 to subtract time units
DECLARE @Result datetime2(7) = DateAdd(millisecond, -1, @YesterdayDateTime); -- Subtract one millisecond
 
Share this answer
 
You can't: the DATETIME type in SQL is not stored as milliseconds, it is stored as a number of ticks since a specific point in time, and a tick is normally 31.250 milliseconds (but is computer dependant): @@TIMETICKS[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900