How can I specify the latest time of day with DateTime

后端 未结 12 1091
不思量自难忘°
不思量自难忘° 2020-12-14 14:03

I am using a System.DateTime object to allow a user to select a date range. The user is only able to select a date (not time) using a third party calendar so I

12条回答
  •  佛祖请我去吃肉
    2020-12-14 15:08

    Your question has already been answered, but IMHO a better way is not to bother attempting to subtract a tick, a second, or whatever from the end of the range, and compare using strictly less than.

    So that if you want all dates in an inclusive range from startDate to endDate, ignoring the time, you could use the following in C#:

    if ((myDate >= startDate.Date) && (myDate < endDate.Date.AddDays(1)))
    {
        // ... it's in the range
    }
    

    or in T-SQL, assuming your @StartDate and @EndDate are exactly midnight, something like:

    WHERE SomeDate >= @StartDate AND SomeDate < DATEADD(d,1,@EndDate)
    

    UPDATE

    Updated example to show an inclusive range in response to comments.

提交回复
热议问题