Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MM:SS to Seconds

Tags:

c#

Is it possible to convert a time such as audio duration into seconds? The format the duration is in is a digital format: 6:30 which represents 6 minutes 30 seconds.

I've tried

TimeSpan.Parse(duration).TotalSeconds

Where duration is 6:30 but it gives an overflow exception.

Should TimeSpan.Parse be able to parse such strings?

Edit:

To update from a question asked in the comments the format is not always MM:SS. If the audio file is over an hour in duration it could also be HH:MM:SS.

like image 498
James Jeffery Avatar asked Dec 11 '25 15:12

James Jeffery


1 Answers

You can use TimeSpan.ParseExact, you need to escape the colon:

TimeSpan duration = TimeSpan.ParseExact("6:30", "h\\:mm", CultureInfo.InvariantCulture);
int seconds = (int)duration.TotalSeconds;  // 23400

Edit: But you should also be able to use TimeSpan.Parse:

duration = TimeSpan.Parse("6:30", CultureInfo.InvariantCulture);

Note that the maximum is 24 hours. If it's longer you need to use DateTime.ParseExact.

But even this long time is working without an overflow (as you've mentioned).

string longTime = "23:33:44";
TimeSpan duration = TimeSpan.Parse(longTime, CultureInfo.InvariantCulture);
int seconds = (int)duration.TotalSeconds; // 84824

You can even pass multiple allowed formats to TimeSpan.ParseExact:

string[] timeformats = { @"m\:ss", @"mm\:ss", @"h\:mm\:ss" };
duration = TimeSpan.ParseExact("6:30", timeformats, CultureInfo.InvariantCulture);
like image 120
Tim Schmelter Avatar answered Dec 14 '25 06:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!