Brian Var
Brian Var

Reputation: 6227

How to parse hours,minutes and seconds from a string to a TimeSpan object?

I'm passing a string as a unit of time via a query string. But when I try to parse the string to a time span object I get a System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code which I gather means there is a problem with way I'm formatting the string to be parsed.

            if (NavigationContext.QueryString.ContainsKey("workTimeSpanPkr"))
            {
                testString = NavigationContext.QueryString["workTimeSpanPkr"];
                //Assign text box string value to a test time span variable.
                 testTm = TimeSpan.ParseExact(testString, @"hh\ \:\ mm\ \:\ ss", CultureInfo.InvariantCulture);

            }

The string being passed over testString when I run it through the debugger is: `"00:15:04"``

Does anyone know the correct format for parsing hours,minutes and seconds?

This is the value I'm trying to parse and the code I'm using to achieve this:

format exception

value of work string

Upvotes: 5

Views: 5941

Answers (1)

toplel32
toplel32

Reputation: 1174

The following works fine for me:

Console.WriteLine(TimeSpan.ParseExact("00:15:04", @"hh\:mm\:ss", CultureInfo.InvariantCulture, TimeSpanStyles.None));

You should remove the whitespace from the format string if you want to match your example of 00:15:04.

Also you may want to read http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx

Upvotes: 5

Related Questions