问题
I have a float that represent a quantity of seconds and I need to format it to match this:
I need to format an elapsed time (in seconds) like this:
HH:mm:ss.fff // Like 01:15:22.150
Here is my code:
TimeSpan timeSpan = new TimeSpan(0, h, m, s, ms);
string time = timeSpan.ToString(@"HH\:mm\:ss.fff"); // Throw a System.FormatException
It don't throw exception if I use ´@"hh:mm:ss"´ but I need the milliseconds...
What is the right string format?
I use this TimeSpan constructor.
回答1:
There's 2 problems:
- There is no
HH
format specifier forTimeSpan
, use lower case versionhh
(see docs) - You need to escape the
.
literal
Which makes the correct version:
string time = timeSpan.ToString(@"hh\:mm\:ss\.fff");
You can also specify literal strings by surrounding them with '
. For example:
string time = timeSpan.ToString("hh':'mm':'ss'.'fff");
来源:https://stackoverflow.com/questions/50609107/system-formatexception-on-timespan-tostring