74

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
2
  • @AJM the docs for Timespan make it pretty explicit what is what with the examples. Mar 31, 2011 at 10:10
  • Just a note that all the components of TimeSpan come in property pairs like this, not just milliseconds. Mintes / TotalMinutes, Hours / TotalHours, etc... Jun 29, 2018 at 13:46

6 Answers 6

87

Simple:

  • Milliseconds are the remaining milliseconds, that don't form a whole second.
  • TotalMilliseconds is the complete duration of the timespan expressed as milliseconds.
80

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

0
4

This hapens because intervalTimespan.Milliseconds returns the millisecond component of the timespan. In your timespan constructor, you only have hour, minute, and second components, which is why the result is 0.

intervalTimespan.TotalMilliseconds gets you the total milliseconds of the timespan.

Example:

// 5 milliseconds
TimeSpan intervalTimespan = new TimeSpan(0, 0,0,0,5);

// returns 5
intervalTimespan.Milliseconds;

// returns 5
intervalTimespan.TotalMilliseconds
2

TimeSpan has other overloads:

TimeSpan(hour, minute, seconds)
TimeSpan(days, hour, minute, seconds)
TimeSpan(days, hour, minute, seconds, milliseconds)

The Milliseconds property returns the actual milliseconds value.

The TotalMilliseconds property returns the overall milliseconds including days, hours, minutes, and seconds.

1

Miliseconds returns just the milliseconds part of your TimeSpan, while TotalMilliseconds calculates how many milliseconds are in time represented by TimeSpan.

In your case, first returns 0 because you have exactly 5 seconds, second returns 5000 because 5s == 5000ms

0
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.