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

前端 未结 5 1640
一生所求
一生所求 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

    Similar to Lukes answer, with a lot more code and room for improvement. BUT it deals with negatives Hours ("-30:15") aswell, so maybe it can help someone.

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

    usage

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

提交回复
热议问题