【问题标题】:Parsing 3 digit input as TimeSpan将 3 位输入解析为 TimeSpan
【发布时间】:2016-06-03 16:34:24
【问题描述】:

用户输入是 555 我希望它是 05:55:00(时间跨度)。如何将其转换为 TimeSpan?使用什么格式?

var a = TimeSpan.ParseExact(/*user input string*/"5:55", new string[] { "%h\\:mm" }, CultureInfo.InvariantCulture);//OK output {05:55:00}
var b = TimeSpan.ParseExact(/*user input string*/"1111", new string[] { "%hmm" }, CultureInfo.InvariantCulture);//OK output {11:11:00}
var c = TimeSpan.ParseExact(/*user input string*/"555", new string[] { "%hmm", "hmm", "hhmm"}, CultureInfo.InvariantCulture);//Exception! None format works.

编辑:详细来说,我想将用户字符串输入格式化为小时和分钟 hh:mm。例如用户输入字符串:

  • “5”为 05:00
  • “12”为 12:00
  • “1111”为 11:11
  • “12:12”为 12:12
  • “4:44”为 4:44
  • 一个不工作的“555”是 5:55(抛出异常)

我现在正在使用:

private static string[] _foramts = {"%hmm", "hmm", "hhmm","%h", "hh\\:mm", "%h\\:mm" };
return TimeSpan.ParseExact((string)value, _foramts, CultureInfo.InvariantCulture).ToString("hh\\:mm");

有了PadLeft,现在也不例外,但是....

var d = TimeSpan.ParseExact(((string)value).PadLeft(4, '0'), new string[]  { "%hmm", "hmm", "hhmm", "%h", "hh\\:mm", "%h\\:mm" }, CultureInfo.InvariantCulture).ToString("hh\\:mm");

“5”现在是 00:05,我希望它是 05:00

【问题讨论】:

  • 我认为您也必须手动完成,将输入作为 string 并执行一些 substring 或将其用作 int 并执行一些 @987654326 @ 和 / 获取您需要的数字。
  • 已经是字符串了。我刚刚找到解决方案,但不是按格式。只需使用用户字符串输入:.PadLeft(4,'0')
  • 这确实是一个糟糕的方法,但有效:TimeSpan ts = TimeSpan.FromSeconds((60 * (int)(int.Parse(input)/100)) + (int.Parse(input) % 100));
  • 现在您可以使用 TimeSpan.FromMinutes 从秒更改为分钟。

标签: c# parsing timespan


【解决方案1】:

问题是H 格式匹配一位或两位数字,具体取决于可用的位数。在您的情况下,它将获取前两位数字“55”,这不是正确的时间。用零填充是解决这个问题的方法:

 var c = TimeSpan.ParseExact(value.PadLeft(4, '0'), new string[] { "%hmm", }, CultureInfo.InvariantCulture);

如果您想处理不同的格式,那么尝试使用一种模式匹配所有可能的输入的普通 if-else 会更容易。

public static TimeSpan Parse(string value) {

    if (value.Length == 1)
    {
        value = value.PadLeft(2, '0');
        value = value.PadRight(4, '0');
    }
    else if (value.Length == 2)
    {
        value = value.PadRight(4, '0');
    }
    else if(value.Length == 3)
    {
        value = value.PadLeft(4, '0');
    }

    return TimeSpan.ParseExact(value, new string[] { "%h\\:mm", "%hmm", "hmm", "hhmm" }, CultureInfo.InvariantCulture);//Exception! None format works.
}

【讨论】:

    【解决方案2】:

    我刚刚找到了解决方案,但不是按格式。只需使用用户字符串输入:.PadLeft(4,'0')。我还是很好奇它可以用格式来完成吗?

    编辑:但现在这不能按预期工作:

    var b = TimeSpan.ParseExact("5", new string[] { "%h" }, CultureInfo.InvariantCulture);
    

    whit .PadLeft(4,'0') 它抛出异常 :(

    【讨论】:

    • var c = TimeSpan.ParseExact("5".PadLeft(4, '0'), "%hmm", CultureInfo.InvariantCulture); 可以工作。
    • Dodałem komentarz do głównego wątku。 Po Twojej zmianie zamiast piątej godziny będę miał pięć po północy。 :) 我编辑了主要问题,在此更改后,用户 intpu "5" 将在午夜后五分钟,而不是预期的早上 5:00
    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    相关资源
    最近更新 更多