Jeankowkow
Jeankowkow

Reputation: 834

System.FormatException on TimeSpan.ToString()

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.

Upvotes: 1

Views: 1282

Answers (1)

DavidG
DavidG

Reputation: 118937

There's 2 problems:

  1. There is no HH format specifier for TimeSpan, use lower case version hh (see docs)
  2. 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");

Upvotes: 7

Related Questions