I need to compare a date range and am missing rows who's date is the upper comparison date but the time is higher than midnight. Is there a way to set the upper comparison's time to 23:59:59?
Just use one day layer than the upper comparison, and < on the upper side instead of <=. That way, you can get times that are even later (fraction of a second) than the one you specified.
Alternatively, compare using the DateTime.Date
property instead of the DateTime directly. This will "strip off" the time portion, so your dates in the search will automatically be treated as midnight.
Yes, this DateTime constructor - http://msdn.microsoft.com/en-us/library/272ba130.aspx allows you to specify the date as well as hours, minutes and seconds.
This is a possible solution:
yourDateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
Why not have the upper comparison being midnight on the day after the last one you're interested in, and then use that with an exclusive comparison?
DateTime upperExclusive = lastInclusive.Date.AddDays(1);
if (dateInclusive >= date && date < upperExclusive)
{
....
}
This feels like a cleaner solution than finding the last second of the day - aside from anything else, you'd still be missing values of 23:59:59.500 etc with your current scheme.
Obligatory plug: I'm not a huge fan of the BCL date/time API. You may want to keep tabs on Noda Time - a port of Joda Time to .NET.
If your doing a compare why don't you compare against less that the start of the next day?
Eg. if it was a Linq query:
someList.Where(x => (currentDaysDate <= x.ItemDate ) && (x.ItemDate < nextDaysDate))
If you are not worried about the time at all, you can use the Date
Property of DateTime
, which returns just the date part (with the time set to 00:00:0000)
if(MyDate.Date >= StartDate.Date && MyDate.Date <= EndDate.Date)
{
//Code here
}
Create an EndOfDay extension method
public static DateTime EndOfDay (this DateTime d)
{
return DateTime.Parse(d.ToShortDateString().Trim() + " 23:59:59");
}