Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# DateTime. Reset time to 0

Tags:

c#

datetime

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?

like image 639
Michael Kostiuchenko Avatar asked Nov 07 '25 18:11

Michael Kostiuchenko


2 Answers

more simply:

return dateTime.Date;

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

like image 130
Marc Gravell Avatar answered Nov 09 '25 08:11

Marc Gravell


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

like image 32
Igor Avatar answered Nov 09 '25 07:11

Igor