SQL Server Time format in 23:59:59 and not 00:00:00

Alex 0 Reputation points
2023-11-04T06:57:13.7233333+00:00

I have the following code. I would like the second (to) date in time format '23:59:59' and not '00:00:00' . How can this be achieved please?

declare @Date datetime 
declare @StartDate datetime 
declare @EndDate DateTime

set @date = GetDate()
Set @StartDate = DATEADD(M, DATEDIFF(M,0,@date),0)
set @EndDate = DATEADD(DD,DATEDIFF(DD,0, @date),0)

select @StartDate,@EndDate
SQL Server | Other
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2023-11-04T08:01:48.2633333+00:00

    Try to execute one more statement:

    set @EndDate = dateadd(second, -1, @EndDate)
    

  2. Erland Sommarskog 121.9K Reputation points MVP Volunteer Moderator
    2023-11-04T10:40:14.2033333+00:00

    Hm, what drives you to ask this question? I suspect this is because your next step to run something like

    WHERE datetimecol BETWEEN @StartDate and @EndDate
    

    If that is the case, do you really want to miss events that occurred 23:59:59.500?

    The correct way to write this is:

    WHERE datetimecol >= cast(getdate() AS date)
      AND datetimecol < dateadd(DAY, 1, cast(getdate() AS date))
    

    Then you don't need bother about seconds.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.