How to Convert string “07:35” (HH:MM) to TimeSpan

后端 未结 4 511
我寻月下人不归
我寻月下人不归 2020-11-28 09:19

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.

Right now I have a \"old fashion style\":

string str         


        
4条回答
  •  半阙折子戏
    2020-11-28 09:54

    Try

    var ts = TimeSpan.Parse(stringTime);
    

    With a newer .NET you also have

    TimeSpan ts;
    
    if(!TimeSpan.TryParse(stringTime, out ts)){
         // throw exception or whatnot
    }
    // ts now has a valid format
    

    This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.

提交回复
热议问题