need to parse a string as mm:ss not as hh:mm

Viewed 86

I need to convert a string values that are mm:ss (examples - "6:12", "59:59", "6:6") and sum them up that are in hh:mm:ss formatted value.

At the moment i'm trying to do a simple thing, but it is throwing me this exception:

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

Here's the example of the code:

string time = "6:14";
TimeSpan ts = TimeSpan.ParseExact(time, "mm:ss", null);
string total = ts.ToString("hh:mm:ss");
1 Answers

You have 2 issues with your code:

  1. You use custom separator : which should be escaped with \
  2. You don't use leading zeroes ("06:14"), that's why you should put m instead of mm (and s instead of ss if "6:6" is a correct value):

Code:

  string time = "6:14";
  TimeSpan ts = TimeSpan.ParseExact(time, @"m\:s", null);
  string total = ts.ToString(@"hh\:mm\:ss"); 
Related