Invalid number of days between two dates

var datetime1 = DateTime.Now;
var datetime2 = DateTime.Now.AddHours(5);
Console.WriteLine((datetime2-datetime1).TotalDays);

      

datetime1

value is 11:30 PM datetime2

The value is the date value plus 5 hours.

The console output should be 2. But the result is 0.2xxxxxxxxxx.

I think above the code to count the number of days per day by two days. Not based on a day of two dates.

What to do to make conclusion 2?

+3


source to share


1 answer


This is not true. TotalDays

displays fractional days, and 5 hours (out of 24) is roughly .2

days.

To display the fact that you are dealing with an interval of two separate days, ignore the time part:



Console.WriteLine((datetime2.Date - datetime1.Date).Days + 1);

      

+5


source







All Articles