如何获得特定日期的最后可能时间

时间:2020-03-06 15:04:48  来源:igfitidea点击:

我正在尝试实现某一天的最后一次可能时间,例如对于Date of 2008-01-23 00:00:00.000,我可能需要通过使用Date上的dateadd函数来实现2008-01-23 23:59:59.999场地?

解决方案

SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))

我以为你先养猫了。如果其他任何人跌跌撞撞地走了,我会把它留在这里。

DateTime now = DateTime.Now;
DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);

我们可以用想要找出的任何一天替换'now'变量

答案是" SELECT DATEADD(ms,-3,'2008-01-24')",解释如下。

从Marc的博客中:

But wait, Marc... you said you like to use BETWEEN, but that query doesn't have one... that's because BETWEEN is inclusive, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:

    SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))

  
  So to do the orders due this month as a BETWEEN query, you can use this:

    SELECT [ID]
    FROM [dbo].[Orders]
    WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)
    AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))

  
  Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't.

第二天开始时应加上-1毫秒(如果我们想获得更好的效果,DateAdd甚至支持纳秒)。

但是很可能我们只是想在比较中使用此值,在这种情况下,它甚至更简单。

而不是像这样:

AND @CompareDate <= [LastTimeforThatday]

或者这个:

@compareDate BETWEEN [StartDate] AND [LastTimeforThatday]

像这样做:

AND @CompareDate < [BeginningOfNextDay]

或者这个:

AND (@CompareDate >= [StartDate] AND @CompareDate < [BeginningOfNextDay])