In the example below, why does the Milliseconds property return 0 but the TotalMilliseconds property return 5000
// 5 seconds
TimeSpan intervalTimespan = new TimeSpan(0, 0, 5);
// returns 0
intervalTimespan.Milliseconds;
// returns 5000.0
intervalTimespan.TotalMilliseconds
Because Milliseconds
returns the Milliseconds portion, and TotalMilliseconds returns the total milliseconds represented by the Timespan
Example: 0:00:05.047
Milliseconds: 47
Total Milliseconds: 5047
This hapens because intervalTimespan.Milliseconds; returns the milisecond component of the timespan.
In your timespan constructor you only have hour minute and second component, that is why the result is 0.
intervalTimespan.TotalMilliseconds - This gets you the total miliseconds of the timespan.
Ex:
// 5 miliseconds
TimeSpan intervalTimespan = new TimeSpan(0, 0,0,0,5);
// returns 5
intervalTimespan.Milliseconds;
// returns 5
intervalTimespan.TotalMilliseconds
It's obvious, Miliseconds
returns just the milisenconds part of your TimeSpan
, while TotalMiliseconds
calculates how many miliseconds are in time represented by TimeSpan
.
In your case, first returns 0
because you have exactly 5 seconds, second returns 5000
because 5s == 5000ms
TimeSpan has other overloads
TimeSpan(hour, minute, seconds)
TimeSpan(days, hour, minute, seconds)
TimeSpan(days, hour, minute, seconds, milliseconds)
Milliseconds property will return the actual milliseconds value
TotalMilliseconds returnss overall milliseconds including days, hour, minute & seconds
One important thing other things don't mention, is that (according to the docs):
The Milliseconds
property represents whole milliseconds, whereas the TotalMilliseconds
property represents whole and fractional milliseconds.
That is also deductible from the remarks of TotalMilliseconds
:
This property converts the value of this instance from ticks to milliseconds.
This has a huge implication, IMO, because if you want the most precise representation in seconds or milliseconds, you must use TotalSeconds
or TotalMilliseconds
properties, both of them are of type double
.