Reputation: 5259
I am trying to parse time using TimeSpan.Parse method; However i get an unexpected result as i am trying to parse this 00:00:45.748
which supposed to be
0 Hours 0 Minutes 45 Seconds 748 Milliseconds
TimeSpan.Parse("00:00:45.748")
Result :
00:00:45.7480000
I want to know why it reads the milliseconds as 7480000
instead of 748
?
Upvotes: 0
Views: 733
Reputation: 4057
00:00:45.7480000 == 00:00:45.748
The difference is simply the number of decimal places on the milliseconds
This will format your output as desired:
var ts = TimeSpan.Parse("00:00:45.748");
Console.WriteLine(string.Format("{0:dd\\:hh\\:mm\\:ss\\.fff}", ts));
The fff is the number of decimal places you want to display (this can be from 1 to 7). See http://msdn.microsoft.com/en-us/library/ee372287.aspx
Note that this will require .NET 4.0 or above
Upvotes: 1
Reputation: 98750
As additional to Oded's answer;
From TimeSpan.Parse Method (String)
ff - Optional fractional seconds, consisting of one to seven decimal digits.
You can use The "FFF" Custom Format Specifier
Like;
TimeSpan ts = TimeSpan.Parse("00:00:45.748");
Console.WriteLine(ts.ToString(@"hh\:mm\:ss\.FFF"), CultureInfo.InvariantCulture);
Output will be;
00:00:45.748
For more informations, take a look at Standard TimeSpan Format Strings
and Custom TimeSpan Format Strings
Upvotes: 1
Reputation: 499002
The result you are showing is that of displaying a TimeSpan
in a textual format.
By default it will show the full range.
The string you have shown actually shows that the parse was successful and you got the right result.
If you want to format the TimeSpan
, use ToString
with an appropriate TimeSpan
format string (.NET 4.0 and above).
There are custom and standard format strings for TimeSpan
.
In your case, it looks like you are looking for:
myTimeSpan.ToString("hh:mm:ss.FFF")
Upvotes: 3