Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong day count between two date

Tags:

c#

datetime

count

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?

like image 472
user2877989 Avatar asked Sep 01 '25 18:09

user2877989


1 Answers

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);
like image 70
Grant Winney Avatar answered Sep 04 '25 08:09

Grant Winney