William Calleja
William Calleja

Reputation: 4175

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

Upvotes: 2

Views: 3461

Answers (4)

Oded
Oded

Reputation: 499002

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

Upvotes: 3

Michal B.
Michal B.

Reputation: 5719

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

You should use hh instead of HH, e.g.:

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

Upvotes: 0

Andrew
Andrew

Reputation: 835

Use should use hh instead of HH.

Upvotes: 0

Chris
Chris

Reputation: 27609

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

Upvotes: 9

Related Questions