How can I specify the latest time of day with DateTime
If you already have a DateTime
object created and want to replace the time with the 11:59:59PM for that given date, then you can use the .Date
property to get the date with time set to 00:00:00 and then add the hours, minutes and seconds. For example:
var dt = yourDateInstance.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
If by latest time, you mean 11:59:59 PM, then this should also work:
var dt = new DateTime(Now.Year, Now.Month, Now.Day, 23, 59, 59);
To get the last instant for today:
DateTime d = new DateTime(Now.Year, Now.Month, Now.Day);
d = d.AddDays(1);
d = d.AddTicks(-1);
In response to your edit, here's what I would do:
DateTime start = new DateTime(Now.Year, Now.Month, Now.Day);
DateTime end = start.AddDays(1).AddTicks(-1);
// Or - just use end = start.AddDays(1), and use a < for comparison
DateTime d = DateTime.Today.AddDays(1).AddTicks(-1);
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.