简体   繁体   中英

Why does TimeSpan string formatting resolve into an Exception?

I have the following line of code in my c# MVC2 Project:

string.Format(@"{0\:HH\:mm}", new TimeSpan(0))

This line is resulting in the following exception:

System.FormatException: Input string was not in a correct format.

Can anybody tell me why? I'm using C#, asp.net, mvc2, and .net framework 4

Two problems. Firstly you should not be escaping the first : . This is necessary as a separator and should not be escaped.

The second is that HH should be hh .

This runs without errors:

string.Format(@"{0:hh\:mm}", new TimeSpan(0))

Your format string uses HH - it should be hh .

See Custom TimeSpan Format Strings on MSDN.

Additionally, your first : shouldn't be escaped - it is part of the placeholder 0 , not a literal.

Together:

string.Format(@"{0:hh\:mm}", new TimeSpan(0))

使用时应使用hh而不是HH。

Check the specification here: http://msdn.microsoft.com/en-us/library/ee372286.aspx

You should use hh instead of HH, eg:

var str = string.Format(@"{0:hh\\:mm}", new TimeSpan(2,2,0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM