【问题标题】:What is a simple way to convert h:m:s and m:s strings to TimeSpan object?将 h:m:s 和 m:s 字符串转换为 TimeSpan 对象的简单方法是什么?
【发布时间】:2017-10-02 12:57:05
【问题描述】:

我正在尝试将时间戳字符串转换为 TimeSpan 对象。 但是,TimeSpan.Parse() 并没有像我预期的那样工作。我会解释原因。

我想转换两种类型的时间戳。

  1. 分:秒
    例如30:53, 1:23, 0:05
  2. 时:分:秒
    例如1:30:53, 2:1:23, 0:0:3

问题是,类型 1 在TimeSpan.Parse() 方法中被解释为小时:分钟格式。

Console.WriteLine(TimeSpan.Parse("12:43"));
// the result I expect -> 0:12:43
// the actual result -> 12:43:00

我用谷歌搜索了这个问题并找到了这个 SO 帖子。
Parse string in HH.mm format to TimeSpan

这使用DateTime.ParseExact() 来解析特定格式的字符串。但是,问题是我需要为类型 1 和 2 使用不同的格式。

// ok
var ts1 = DateTime.ParseExact("7:33", "m:s", CultureInfo.InvariantCulture).TimeOfDay;
// throws an exception
var ts2 = DateTime.ParseExact("1:7:33", "m:s", CultureInfo.InvariantCulture).TimeOfDay;
// throws an exception
var ts3 = DateTime.ParseExact("7:33", "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;
// ok
var ts4 = DateTime.ParseExact("1:7:33", "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;

我还查看了 MSDN,但没有帮助。
https://msdn.microsoft.com/ja-jp/library/se73z7b9(v=vs.110).aspx

所以我想出的解决方案如下。

A. DateTime.ParseExact 与 if

string s = "12:43";
TimeSpan ts;
if (s.Count(c => c == ':') == 1)
    ts = DateTime.ParseExact(s, "m:s", CultureInfo.InvariantCulture).TimeOfDay;
else
    ts = DateTime.ParseExact(s, "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;

B. TimeSpan.Parse 与 if

string s = "12:43";
if (s.Count(c => c == ':') == 1)
    s = "0:" + s;
var ts = TimeSpan.Parse(s);

但它们都很长而且不“酷”。感觉就像我在重新发明轮子。我不想要他们,任何接受者?

那么将 h:m:s 和 m:s 字符串转换为 TimeSpan 对象的简单方法是什么?

提前致谢!

【问题讨论】:

    标签: c# datetime datetime-format


    【解决方案1】:

    您可以在TimeSpan.ParseExact 中指定几种 格式:

      string source = "17:29";
    
      TimeSpan result = TimeSpan.ParseExact(source, 
        new string[] { @"h\:m\:s", @"m\:s" }, 
        CultureInfo.InvariantCulture);
    

    在上面的代码中,我们先尝试h:m:s 格式,如果第一种格式失败,然后再尝试m:s

    测试:

      string[] tests = new string[] { 
         // minutes:seconds
        "30:53", "1:23", "0:05", 
         // hours:minutes:seconds 
        "1:30:53", "2:1:23", "0:0:3" };
    
      var report = string.Join(Environment.NewLine, tests
        .Select(test => TimeSpan.ParseExact(
           test, 
           new string[] { @"h\:m\:s", @"m\:s" },
           CultureInfo.InvariantCulture)));
    
      Console.Write(report);
    

    结果:

    00:30:53
    00:01:23
    00:00:05
    01:30:53
    02:01:23
    00:00:03
    

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2021-07-21
      • 2012-08-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多