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

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

    Normally one would use TimeSpan.ParseExact where a specific format is required. But the only hours formats that can be specified are as parts of days (see Custom TimeSpan Format Strings).

    Therefore you will need to do the work yourself:

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

    (But with some error checking.)

    The three integer constructor of timespan allows hours >= 24 overflowing into the days count.

提交回复
热议问题