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?
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 AMinstead of3/25/2020 00:00:00whenConsole.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With