[c#] How to Convert string "07:35" (HH:MM) to TimeSpan

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 stringTime = "07:35";
string[] values = stringTime.Split(':');

TimeSpan ts = new TimeSpan(values[0], values[1], 0);

This question is related to c# timespan

The answer is



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.


You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.