C# Traps and Pitfalls: TimeSpan.Days and .TotalDays
TimeSpan.Days returns an int representing whole days (positive or negative), while TimeSpan.TotalDays returns a double representing whole and fractional days (positive or negative).
All of these are obvious for positive timespan values:
new TimeSpan(2, 18, 0, 0).Days == 2
new TimeSpan(2, 18, 0, 0).TotalDays == 2.75
new TimeSpan(2, 18, 0, 0).ToString() == "2.18:00:00"
new TimeSpan(2, -18, 0, 0).Days == 1
new TimeSpan(2, -18, 0, 0).TotalDays == 1.25
new TimeSpan(2, -18, 0, 0).ToString() == "1.06:00:00"
But may be unexpected to some for negative timespan values:
new TimeSpan(-2, -18, 0, 0).Days == -2
new TimeSpan(-2, -18, 0, 0).TotalDays == -2.75
new TimeSpan(-2, -18, 0, 0).ToString() == "-2.18:00:00"
new TimeSpan(-2, 18, 0, 0).Days == -1
new TimeSpan(-2, 18, 0, 0).TotalDays == -1.25
new TimeSpan(-2, 18, 0, 0).ToString() == "-1.06:00:00"
The key is that each component of a TimeSpan with negative value is itself a negative value or 0, and vice versa.
And here is the relationship between TimeSpan.TotalDays
(x) and TimeSpan.Days
(y):
We can see that the span when TimeSpan.Days
(y) is 0 extends to 2 days actually. Run the following code to see it for real:
var a = new TimeSpan(-1, 0, 0, 0);
Console.WriteLine(a.TotalDays); // -1
Console.WriteLine(a.Days); // -1
var b = new TimeSpan(-0, -23, -59, -59);
Console.WriteLine(b.TotalDays); // -0.999988425925926
Console.WriteLine(b.Days); // 0
var c = new TimeSpan( 0, 23, 59, 59);
Console.WriteLine(c.TotalDays); // 0.999988425925926
Console.WriteLine(c.Days); // 0
var d = new TimeSpan( 1, 0, 0, 0);
Console.WriteLine(d.TotalDays); // 1
Console.WriteLine(d.Days); // 1
Console.WriteLine(c - b); // 1.23:59:58
Console.WriteLine(d - a); // 2.00:00:00
This relationship applies to TotalHours/Hours, TotalMinutes/Minutes, etc. as well.