How do i convert HH:MM:SS into just seconds using C#.net?


Question

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?

1
24
3/25/2009 3:16:43 PM

Accepted Answer

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;
70
3/25/2009 3:15:23 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon