c# DateTime. Reset time to 0

Viewed 2142

I have dateTime = 3/25/2020 1:25:46 PM Can I reset time to zero? 3/25/2020 00:00:00

Here is a demo. In this case dateTime is 3/25/2020 12:00:00 AM

class Program
{
    static  void Main(string[] args)
    {

        var datetime = DateTime.Now;
        datetime = ResetTimeToStartOfDay(datetime);

        Console.WriteLine(datetime);
        Console.ReadLine();
    }

    public static DateTime ResetTimeToStartOfDay(DateTime dateTime)
    {
        return new DateTime(
           dateTime.Year,
           dateTime.Month,
           dateTime.Day,
           0, 0, 0, 0);
    }
}

How to reset the date to the beginning of the day?

3 Answers

more simply:

return dateTime.Date;

But note that in the specific case of DateTime.Now you could just use DateTime.Today instead.

How to reset the date to the beginning of the day?

You already are in your method ResetTimeToStartOfDay although there is an easier way to do it with dateTime.Date which is functionally equivalent.

So your question now becomes:

Why do you see 3/25/2020 12:00:00 AM instead of 3/25/2020 00:00:00 when Console.WriteLine(datetime); is called.

When you call ToString() on the DateTime instance, which happens implicitly in Console.WriteLine(datetime);, the displayed format matches the culture of the current thread which then displays the time using AM/PM. If you want to display the date as 3/25/2020 00:00:00 then call ToString() explicitly and pass a format string like M/d/yyyy HH:mm:ss

Console.WriteLine(datetime.ToString("M/d/yyyy HH:mm:ss"));

See also Custom date and time format strings

Try:

public static DateTime SetTimeToZero(DateTime YourDate)
{
    return new DateTime(YourDate.Year, YourDate.Month, YourDate.Day, 0, 0, 0);
}

or you can create an ExtensionMethod and use inside your project:

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

How to use ExtensionMethod:

yourDatetime.SetTimeToZero(date);
Related