tags:

views:

186

answers:

4

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.ToDouble(span.Split(':')[0])).Add(TimeSpan.FromMinutes(Convert.ToDouble((span.Split(':')[1]))));

This does not seem too elegant.

A: 

See this question (duplicate).

Ando
it's not really a duplicate, that one is not about greater then 24.
Stefan Steinegger
+2  A: 

If you're certain that the format will always be "HH:mm" then try something like this:

string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]),    // hours
                           int.Parse(span.Split(':')[1]),    // minutes
                           0));                              // seconds
LukeH
A: 

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.

Richard
+1  A: 

Similar to Luke's one, but handles amount of hours higher than 99:

   String span = "123:45";
   Int32 colon = span.IndexOf(':');
   TimeSpan timeSpan = new TimeSpan(Int32.Parse(span.Substring(0, colon - 1)),
                                    Int32.Parse(span.Substring(colon)), 0);

Obviously it assumes the orignal string is well-formed (composed of two parts separated by colon and parsable to an integer number).

Erik Burigo
I reckon Luke's one handles > 99 doesn't it?
jlp
@Erik, @jlp: Yes, mine handles hours greater than 99 just fine, although my original answer didn't (before I edited it half an hour ago). Maybe Erik was looking at the old answer.
LukeH
@Luke: Yup! Exactly as you replied here ;)
Erik Burigo