问题
I created a TimeSpan
this way
TimeSpan ts = new Timespan();
// Do some addition and subtraction on it
Then I am saving it to a file using this
string.Format("{0}:{1}:{2}:{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.MilliSeconds);
Various values returned from it are like this
0:0:4:410
0:0:1:425
0:0:1:802
0:0:1:509
0:0:1:674
0:0:1:628
0:0:2:76
How to convert it back to TimeSpan.
I am using
TimeSpan.ParseExact("0:0:4:410", "h:m:s:fff", null);
but it is giving me error Input String is not in correct format.
Where am I wrong?
回答1:
I believe you need to parse the colons, basically. I would also suggest using the invariant culture instead of the current thread culture:
var ts = TimeSpan.ParseExact("0:0:4:410", @"h\:m\:s\:fff",
CultureInfo.InvariantCulture);
From the documentation:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
I would also suggest using a format of h:mm:ss.fff
instead - I believe this would be clearer than your current format. Note that you can use the format directly instead of your currently formatting approach:
const string TimeSpanFormat = @"h\:mm\:ss\.fff";
string text = ts.ToString(TimeSpanFormat, CultureInfo.InvariantCulture);
...
TimeSpan parsed = TimeSpan.ParseExact(text, TimeSpanFormat,
CultureInfo.InvariantCulture);
回答2:
you will have to escape the colons
: when you are doing the parse
TimeSpan.ParseExact("0:0:4:410", @"h\:m\:s\:fff", null)
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
was bitten some time back
回答3:
Try this:
TimeSpan timeSpan = TimeSpan.ParseExact("0:0:4:410", @"h\:m\:s\:fff", null);
来源:https://stackoverflow.com/questions/12036972/timespan-parseexact-giving-error