如何将小时大于24的字符串解析为TimeSpan?

问题描述 投票:0回答:6

如何在 C# 中将 30:15 这样的字符串解析为 TimeSpan? 30:15意味着30小时15分钟。

string span = "30:15";
TimeSpan ts = TimeSpan.FromHours(
    Convert.ToDouble(span.Split(':')[0])).
  Add(TimeSpan.FromMinutes(
    Convert.ToDouble((span.Split(':')[1]))));

这看起来不太优雅。

c# timespan
6个回答
37
投票

如果您确定格式始终为“HH:mm”,请尝试以下操作:

string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]),    // hours
                           int.Parse(span.Split(':')[1]),    // minutes
                           0);                               // seconds

5
投票

类似于卢克的回答:

String span = "123:45";
Int32 colon = span.IndexOf(':');
TimeSpan timeSpan = new TimeSpan(Int32.Parse(span.Substring(0, colon)),
                                 Int32.Parse(span.Substring(colon + 1)), 0);

显然,它假设原始字符串格式良好(由用冒号分隔的两部分组成,并且可解析为整数)。


4
投票

我正在使用我很久以前设计的一个简单方法,今天刚刚发布到我的博客上:

public static class TimeSpanExtensions
{
    static int[] weights = { 60 * 60 * 1000, 60 * 1000, 1000, 1 };

    public static TimeSpan ToTimeSpan(this string s)
    {
        string[] parts = s.Split('.', ':');
        long ms = 0;
        for (int i = 0; i < parts.Length && i < weights.Length; i++)
            ms += Convert.ToInt64(parts[i]) * weights[i];
        return TimeSpan.FromMilliseconds(ms);
    }
}

这比之前提供的更简单的解决方案可以处理更多的情况,但也有其自身的缺点。我在here进一步讨论它。

现在,如果您使用 .NET 4,您可以将 ToTimeSpan 实现缩短为:

public static TimeSpan ToTimeSpan(this string s)
{
    return TimeSpan.FromMilliseconds(s.Split('.', ':')
        .Zip(weights, (d, w) => Convert.ToInt64(d) * w).Sum());
}

如果您不介意使用横屏状态,甚至可以将其设为单行...


1
投票

与卢克的回答类似,有更多的代码和改进的空间。但它也处理负面时间(“-30:15”),所以也许它可以帮助某人。

public static double GetTotalHours(String s)
    {
        bool isNegative = false;
        if (s.StartsWith("-"))
            isNegative = true;

        String[] splitted = s.Split(':');
        int hours = GetNumbersAsInt(splitted[0]);
        int minutes = GetNumbersAsInt(splitted[1]);

        if (isNegative)
        {
            hours = hours * (-1);
            minutes = minutes * (-1);
        }
        TimeSpan t = new TimeSpan(hours, minutes, 0);
        return t.TotalHours;
    }

public static int GetNumbersAsInt(String input)
        {
            String output = String.Empty;
            Char[] chars = input.ToCharArray(0, input.Length);
            for (int i = 0; i < chars.Length; i++)
            {
                if (Char.IsNumber(chars[i]) == true)
                    output = output + chars[i];
            }
            return int.Parse(output);
        }

用法

double result = GetTotalHours("30:15");
double result2 = GetTotalHours("-30:15");

1
投票

基于 Jan 的回答

.NET 5

    /// <summary>
    /// 1 number : hours    "0" to "0:0:0" ,    "-1" to "-01:00:00"
    /// 2 numbers : hours, minutes    "1:2" to "01:02:00"
    /// 3 numbers : hours, minutes, seconds    "1:2:3" to "01:02:03"
    /// 4 numbers : days, hours, minutes, seconds    "1:2:3:4" to "1.02:03:04"
    /// Any char can be used as separator.    "1,2 3aaaa4" to "1.02:03:04"
    /// </summary>
    /// <param name="timeSpanString"></param>
    /// <param name="ts"></param>
    /// <returns>true : conversion succeeded</returns>
    public static bool GetTimeSpan(string timeSpanString, ref TimeSpan ts)
    {

        bool isNegative = timeSpanString.StartsWith("-"); // "-1:2:3" is true
        var digitsString = Regex.Replace(timeSpanString, "[^0-9]", " "); // "-1:2:3" to " 1 2 3" 
        var s = digitsString.Split(' ', StringSplitOptions.RemoveEmptyEntries); // "1","2","3"

        int days = 0;
        int hours = 0;
        int minutes = 0;
        int seconds = 0;

        switch (s.Length)
        {
            case 1:
                hours = int.Parse(s[0]);
                break;

            case 2:
                hours = int.Parse(s[0]);
                minutes = int.Parse(s[1]);
                break;

            case 3:
                hours = int.Parse(s[0]);
                minutes = int.Parse(s[1]);
                seconds = int.Parse(s[2]);
                break;

            case 4:
                days = int.Parse(s[0]);
                hours = int.Parse(s[1]);
                minutes = int.Parse(s[2]);
                seconds = int.Parse(s[3]);
                break;

            default:
                return false; //no digits or length > 4
        }

        if (isNegative)
        {
            ts = new TimeSpan(-days, -hours, -minutes, -seconds);
        }
        else
        {
            ts = new TimeSpan(days, hours, minutes, seconds);
        }

        return true;
    }

时间跨度助手 将 TimeSpan 转换为超过 24 小时的数字。 TimeSpan 转换器,文本框规则。


0
投票

通常在需要特定格式的情况下会使用

TimeSpan.ParseExact
。但唯一可以指定的小时格式是天的一部分(请参阅自定义时间跨度格式字符串)。

因此您需要自己完成这项工作:

string input = "30:24";
var parts = input.Split(':');
var hours = Int32.Parse(parts[0]);
var minutes = Int32.Parse(parts[1]);
var result = new TimeSpan(hours, minutes, 0);

(但有一些错误检查。)

timespan 的三个整数构造函数允许小时 >= 24 溢出到天数中。

© www.soinside.com 2019 - 2024. All rights reserved.