Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

datetime

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?

like image 489
Andrew Avatar asked Mar 25 '09 15:03

Andrew


People also ask

How do you convert HH mm SS to seconds?

To convert hh:mm:ss to seconds:Convert the hours to seconds, by multiplying by 60 twice. Convert the minutes to seconds by multiplying by 60 .

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.


2 Answers

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; 
like image 155
Michael Piendl Avatar answered Sep 20 '22 03:09

Michael Piendl


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

like image 28
Jesper Fyhr Knudsen Avatar answered Sep 20 '22 03:09

Jesper Fyhr Knudsen