tags:

views:

3274

answers:

3

Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?

+13  A: 

It looks like a timespan. So simple parse the text and get the seconds.

string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;
michl86
Why are you storing seconds in a double?
Alan
The property TotalSeconds of TimeSpan is double - i don't know why...
michl86
Cuz it supports fractional seconds. Interesting. Thx.
Alan
Now i know why! Expect the following TimeSpan: "1:30:45.12". Then the result is 5445.12.
michl86
cheers mich186 :)
Andi
The TotalSeconds is a double because it returns the entire TimeSpan as seconds, where as the Seconds property only returns the actual seconds, which were what was asked for.
Arkain
+7  A: 

TimeSpan.Parse() will parse a formatted string.

So

TimeSpan.Parse("03:33:12").TotalSeconds;
Alan
Why aren't you storing the value of TotalSeconds in a double? *grin*
Jeff Yates
The world may never know ;)
Alan
+9  A: 

You can use the parse method on aTimeSpan.

http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx

TimeSpan ts = TimeSpan.Parse( "10:20:30" );
double totalSeconds = ts.TotalSeconds;

The TotalSeconds property returns the total seconds if you just want the seconds then use the seconds property

int seconds = ts.Seconds;

Seconds return '30'. TotalSeconds return 10 * 3600 + 20 * 60 + 30

Arkain
Very detailed answer! Good style! Thanks.
michl86
agreed, left answer flag with mich as he answered first though
Andi