James Jeffery
James Jeffery

Reputation: 12599

Convert MM:SS to Seconds

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.

Upvotes: 2

Views: 2977

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460360

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);

Upvotes: 6

Nick Udell
Nick Udell

Reputation: 2501

A simple string manipulation is an alternative way to do it, posted purely for reference. I'd recommend the TimeSpan.ParseExact() method instead.

string[] splitDuration = duration.Split(':');

int minutes = Convert.ToInt32(splitDuration[0]);
int seconds = minutes * 60 + Convert.ToInt32(splitDuration[1]);

Upvotes: 4

Related Questions