Setting time to 23:59:59

65,468

Solution 1

This is a possible solution:

yourDateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

Solution 2

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.

Solution 3

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))

Solution 4

Just use one day later 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.

Solution 5

Create an EndOfDay extension method

 public static DateTime EndOfDay (this DateTime d)
    {
        return DateTime.Parse(d.ToShortDateString().Trim() + " 23:59:59");
    }
Share:
65,468
Mike Wills
Author by

Mike Wills

After going to school to become a network administrator, Mike, fell in love with programming. He has been a midrange (IBM i, iSeries, AS/400) developer since 2000. He has since added ASP.NET to to his toolbox (around 2006) and now does dual duty writing/supporting green-screen applications and ASP.NET internet and intranet applications. He does a lot of integration between the IBM i and ASP.NET. Besides his programming day job, he dabbles in PHP and many other areas of tech. You can find him on his website, @MikeWills, Facebook, and Google+

Updated on August 31, 2020

Comments

  • Mike Wills
    Mike Wills over 3 years

    Possible Duplicate:
    How can I specify the latest time of day with DateTime

    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?