How to parse string with hours greater than 24 to TimeSpan?

前端 未结 5 1644
一生所求
一生所求 2020-11-29 07:58

How to parse string like 30:15 to TimeSpan in C#? 30:15 means 30 hours and 15 minutes.

string span = \"30:15\";
TimeSpan ts = TimeSpan.FromHours(
    Convert         


        
5条回答
  •  广开言路
    2020-11-29 08:32

    I'm using a simple method that I devised a long time ago and just posted today to my blog:

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

    This can handle a lot more situations than the simpler solutions provided before, but has its own shortcomings. I discuss it further here.

    Now, if you're in .NET 4 you can shorten the ToTimeSpan implementation to:

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

    You can even make it an one-liner if you don't mind using horizontal screen state...

提交回复
热议问题