Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
like image 696
VAAA Avatar asked Jun 23 '14 14:06

VAAA


People also ask

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property.

How to parse string to TimeSpan in c#?

Parse(String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.


3 Answers

While correct that this will work:

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

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

like image 173
Matt Johnson-Pint Avatar answered Oct 20 '22 01:10

Matt Johnson-Pint


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.

like image 30
faester Avatar answered Oct 19 '22 23:10

faester


Use TimeSpan.Parse to convert the string

http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx

like image 4
adjan Avatar answered Oct 20 '22 00:10

adjan