DateTime.Now - first and last minutes of the day

Is there any easy way to get a DateTime's "TimeMin" and "TimeMax"?

TimeMin: The very first moment of the day. There is no DateTime that occurs before this one and still occurs on the same day.

TimeMax: The very last moment of the day. There is no DateTime that occurs after this one and still occurs on the same day.

These values would be helpful for filtering and doing date-related queries.


Solution 1:

Here are two extensions I use to do exactly that.

    /// <summary>
    /// Gets the 12:00:00 instance of a DateTime
    /// </summary>
    public static DateTime AbsoluteStart(this DateTime dateTime)
    {
        return dateTime.Date;
    }

    /// <summary>
    /// Gets the 11:59:59 instance of a DateTime
    /// </summary>
    public static DateTime AbsoluteEnd(this DateTime dateTime)
    {
        return AbsoluteStart(dateTime).AddDays(1).AddTicks(-1);
    }

This allows you to write:

DateTime.Now.AbsoluteEnd() || DateTime.Now.AbsoluteStart()

or

DateTime partyTime = new DateTime(1999, 12, 31);

Console.WriteLine("Start := " + partyTime.AbsoluteStart().ToString());
Console.WriteLine("End := " + partyTime.AbsoluteEnd().ToString());

Solution 2:

I'd use the following:

DateTime now = DateTime.Now;
DateTime startOfDay = now.Date;
DateTime endOfDay = startOfDay.AddDays(1);

and use < endOfDay instead of <= endOfDay. This will mean that it will work regardless of whether the precision is minutes, seconds, milliseconds, ticks, or something else. This will prevent bugs like the one we had on StackOverflow (though the advice was ignored).

Note that it is important to only call DateTime.Now once if you want the start and end of the same day.

Solution 3:

try

//midnight this morning
DateTime timeMin = DateTime.Now.Date; 
//one tick before midnight tonight
DateTime timeMax = DateTime.Now.Date.AddDays(1).AddTicks(-1) 

If you are using this for filtering, as your comments suggest, it is probably a good idea to save DateTime.Now into a variable, just in case the date ticks over between the two calls. Very unlikely but call it enough times and it will inevitably happen one day (night rather).

DateTime currentDateTime = DateTime.Now;
DateTime timeMin = currentDateTime.Date; 
DateTime timeMax = currentDateTime.Date.AddDays(1).AddTicks(-1)

Solution 4:

One small tweak to hunter's solution above... I use the following extension method to get the end of the day:

public static DateTime EndOfDay(this DateTime input) {
    return input.Date == DateTime.MinValue.Date ? input.Date.AddDays(1).AddTicks(-1) : input.Date.AddTicks(-1).AddDays(1);
}

This should handle cases where the DateTime is either DateTime.MinValue or DateTime.MaxValue. If you call AddDays(1) on DateTime.MaxValue, you will get an exception. Similarly, calling AddTicks(-1) on DateTime.MinValue will also throw an exception.