如何将字符串中的小时、分钟和秒解析为 TimeSpan 对象?

Bri*_*n J 5 c# parsing timespan string-formatting

我通过查询字符串传递一个字符串作为时间单位。但是,当我尝试将字符串解析为时间跨度对象时,我得到了一个System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code我收集的信息,这意味着我格式化要解析的字符串的方式存在问题。

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

            }
Run Code Online (Sandbox Code Playgroud)

当我通过调试器运行它时传递​​的字符串 testString是:“00:15:04”``

有谁知道解析小时、分钟和秒的正确格式?

这是我试图解析的值以及我用来实现此目的的代码:

格式异常

工作字符串的值

top*_*l32 5

以下对我来说效果很好:

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

如果您想匹配您的示例,您应该从格式字符串中删除空格00:15:04

您也可能想阅读http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx