What's a good way to check if two datetimes are on the same calendar day in TSQL?

前端 未结 10 1414
小鲜肉
小鲜肉 2021-02-12 02:15

Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which suck

10条回答
  •  暖寄归人
    2021-02-12 03:19

    You pretty much have to keep the left side of your where clause clean. So, normally, you'd do something like:

    WHERE MyDateTime >= @activityDateMidnight 
          AND MyDateTime < (@activityDateMidnight + 1)
    

    (Some folks prefer DATEADD(d, 1, @activityDateMidnight) instead - but it's the same thing).

    The TimeZone table complicates matter a bit though. It's a little unclear from your snippet, but it looks like t.TheDateInTable is in GMT with a Time Zone identifier, and that you're then adding the offset to compare against @activityDateMidnight - which is in local time. I'm not sure what ds.LocalTimeZone is, though.

    If that's the case, then you need to get @activityDateMidnight into GMT instead.

提交回复
热议问题