var datetime1 = DateTime.Now;
var datetime2 = DateTime.Now.AddHours(5);
Console.WriteLine((datetime2-datetime1).TotalDays);
datetime1
value is 11:30 PM
datetime2
value is a date time value plus more 5 hours.
The console output must be 2. But the result is 0.2xxxxxxxxxx.
I thinks above code calculate days count base on hour of two date. Not based on day of two date.
What should I do to make the output is 2?
It's not wrong. The TotalDays
displays fractional days, and 5 hours (out of 24) is roughly .2
days.
To display the fact that you're dealing with a span of two separate days, ignore the time portion:
Console.WriteLine((datetime2.Date - datetime1.Date).Days + 1);
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