Reputation: 10033
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?
Upvotes: 33
Views: 68788
Reputation: 84
//Added code to handle invalid strings
string time = null; //"";//"1:31:00";
string rv = "0";
TimeSpan result;
if(TimeSpan.TryParse(time, out result))
{
rv = result.TotalSeconds.ToString();
}
retrun rv;
Upvotes: 1
Reputation: 31337
This code allows the hours and minutes components to be optional. For example,
"30" -> 24 seconds
"1:30" -> 90 seconds
"1:1:30" -> 3690 seconds
int[] ssmmhh = {0,0,0};
var hhmmss = time.Split(':');
var reversed = hhmmss.Reverse();
int i = 0;
reversed.ToList().ForEach(x=> ssmmhh[i++] = int.Parse(x));
var seconds = (int)(new TimeSpan(ssmmhh[2], ssmmhh[1], ssmmhh[0])).TotalSeconds;
Upvotes: 2
Reputation: 7927
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
Upvotes: 29
Reputation: 46813
TimeSpan.Parse() will parse a formatted string.
So
TimeSpan.Parse("03:33:12").TotalSeconds;
Upvotes: 12
Reputation: 2884
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;
Upvotes: 88