How to get the start and end times of a day

I am surprised to see how an incorrect answer received so many upvotes:

Wrong value

The correct version would be as follows:

public static DateTime StartOfDay(this DateTime theDate)
{
    return theDate.Date;
}

public static DateTime EndOfDay(this DateTime theDate)
{
    return theDate.Date.AddDays(1).AddTicks(-1);
}

You could define two extension methods somewhere, in a utility class like so :

public static DateTime EndOfDay(this DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
}

public static DateTime StartOfDay(this DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
}

And then use them in code like so :

public DoSomething()
{
    DateTime endOfThisDay = DateTime.Now.EndOfDay();
}

Tags:

C#

Datetime