【问题标题】:How to parse hours,minutes and seconds from a string to a TimeSpan object?如何将小时、分钟和秒从字符串解析为 TimeSpan 对象?
【发布时间】:2014-11-01 07:49:13
【问题描述】:

我通过查询字符串将字符串作为时间单位传递。但是当我尝试将字符串解析为时间跨度对象时,我得到一个 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);

            }

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

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

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

【问题讨论】:

  • 为什么字符串文字 (@) 上的所有转义序列?听起来解析格式应该是"hh:mm:ss"
  • 真的是这样引用的吗? - 单,双,字符串,双,单,单 - 这是不对的
  • 通过这么简单的解析,您可能只需要使用TimeSpan.ParseTimeSpan.TryParse
  • @BradleyDotNET 一个常见的错误。DateTime 和 TimeSpan 格式不一样。 msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx
  • @L.B 每天学习新东西。感谢您的链接!

标签: c# parsing timespan string-formatting


【解决方案1】:

以下对我来说很好用:

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

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

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

【讨论】:

  • 我最初是在解析文本框中输入的实际字符串,这就是上述格式不起作用的原因。我传递的新字符串是 TimeSpan 类型,因此没有空格是问题所在。上述解决方案有效,谢谢
  • 我重新运行了代码,又遇到格式异常,奇怪。这就是我根据您的示例进行解析的方式:workTm = TimeSpan.ParseExact(wrkString, @"hh\:mm\:ss", CultureInfo.InvariantCulture, TimeSpanStyles.None);
  • 知道为什么会这样吗?
  • @BrianJ 如果它正在发生,这意味着您的 wrkString 字符串不是您声称的那样。从调试器发布字符串的屏幕截图。
  • 刚刚添加了 wrkString 值调试器的屏幕截图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2018-09-28
  • 2015-11-09
相关资源
最近更新 更多