1

I know there are a lot of questions like this, but I can't seem to find an answer for mine.

I have this line of C# code:

var x = TimeSpan.ParseExact("800", "hmm", CultureInfo.InvariantCulture);

And it throws an exception saying that the input format was invalid. If I put "0800" and "hhmm", it works. I've seen people use the single "h" in TimeSpan-Conversions, so it has to be possible to do so. There are also no special letters that would need to be escaped.

I tried using CurrentCulture instead of InvariantCulture, but that didn't change anything. Right now, I'm padding my strings to have 0s on the left side, but I would like to know, why the TimeSpan-Parsing failed.

Manuel Hoffmann
  • 539
  • 1
  • 7
  • 23

1 Answers1

2

I'm don't know why that is so or where it is documented, but three digit timespans seem not to be supported in TimeSpan.ParseExact. So you could workaround it by padding it with leading zeros:

string ts = "800";
var x = TimeSpan.ParseExact(ts.PadLeft(4, '0'), "hhmm", CultureInfo.InvariantCulture);

I guess that the reason why TimeSpan cannot parse this is related to the reason why DateTime.ParseExact cannot parse 7 digits with one or two digit month and without a delimiter.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @Manuel Hoffmann: _"Right now, I'm padding my strings to have 0s on the left side"_ whoops, until now i haven't seen that this is already your workaround. Maybe my last sentence has some added value. – Tim Schmelter Aug 12 '14 at 10:46
  • You're right, I already do that. What an odd behaviour on C#'s side. – Manuel Hoffmann Aug 12 '14 at 15:43