Get the max possible time of a date SQL Server

Viewed 1385

What I am trying to do is take a date in SQL Server and find the last possible hour, minute, second, and millisecond of that date.

So if the date is this: 2021-02-16 13:08:58.620

I would like to return: 2021-02-16 23:59:59.999

I have tried something like this but it is not working and I guess that I am missing something where it is converting the time and keeping the hour, minute, second and millisecond of that date

Select 
    DateAdd(MILLISECOND, -1, (Convert(datetime, DATEADD(day, 1, DateValue), 101))) as lastPossibleDate
From 
    Table1
4 Answers

Turn it into a date to truncate the time, add a day, turn it back to a datetime, subtract a millisecond...

declare @Test datetime2(3) = '2021-02-16 13:08:58.620';

select dateadd(millisecond, -1, convert(datetime2(3),dateadd(day, 1, convert(date, @Test))));
Result
2021-02-16 23:59:59.999

Note if you use straight datetime rather than datetime(2) your accuracy is only down to 3ms. datetime(2) is the recommended datetime datatype to use.

Another simply way would be to cast your datetime to a date and just concatenate it with the maximum possibly time for your given precision. If you want accuracy to 3 decimal places you need to use datetime2(3)

declare @date datetime='20210216 13:08:58.620';

select Convert(datetime2(3),Concat(convert(date,@date),' 23:59:59.999'));

Just another option via format()

declare @Test datetime2(3) = '2021-02-16 13:08:58.620';

select convert(datetime2(3),format(@Test,'yyyy-MM-dd 23:59:59.999'))

For datetime datatype, the maximum value possible for time is : 23:59:59.997

Datetime from MSDN

We can use DateTimeFromParts to derive maximum possible datetime value for the day.

DECLARE @datevalue datetime = '2021-02-16 13:08:58.620'

SELECT DATETIMEFROMPARTS ( year(@datevalue), month(@datevalue), day(@datevalue), 23, 59, 59, 997 )  as maxPossibleValueForDay 
maxPossibleValueForDay
2021-02-16 23:59:59.997
Related