System.FormatException on TimeSpan.ToString()

三世轮回 提交于 2020-01-15 10:39:13

问题


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:

  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");


来源:https://stackoverflow.com/questions/50609107/system-formatexception-on-timespan-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!