tags:

views:

242

answers:

7

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?

+1  A: 

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.

Reed Copsey
A: 

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.

logicnp
A: 

This is a possible solution:

yourDateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
Webleeuw
This worked. Thank you!
Mike Wills
Just hope that there's nothing with a time of 23:59:59.500.
Jon Skeet
This is data that is entered between 7:00 am and 4:00 pm. The only thing that could potentially be a problem doesn't pass a time to this database I am working with. I am sure I'll be fine.Definitely something another looking for a similar solution should be worried about.
Mike Wills
I understand the downvoting, it's not the best or most charming solution. However, I'm glad it answered the question (as technically, it complied with the question stated ;-)).
Webleeuw
+11  A: 

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.

Jon Skeet
+3  A: 

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))
Kelsey
A: 

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
}
adharris
A: 

Create an EndOfDay extension method

 public static DateTime EndOfDay (this DateTime d)
    {
        return DateTime.Parse(d.ToShortDateString().Trim() + " 23:59:59");
    }
asp316
The behavior of DateTime.Parse() and ToShortDateString() depends on current system locale. Your code will fail in some non-English locales.
Daniel