2

I want to extract the TotalSeconds from a String with format "MM:SS". For instance: 01:20 I spect 80 (seconds)

I do it and I get an Exception:

TimeSpan.ParseExact(time.ToString(), "mm:ss", System.Globalization.CultureInfo.CurrentCulture).TotalSeconds;

What do I do wrong??

Thanks!

MrScf
  • 2,407
  • 5
  • 27
  • 40
  • Yes, I found the solution in [link](http://stackoverflow.com/questions/11719055/why-does-timespan-parseexact-not-work) Format: "mm\\:ss" – MrScf Nov 27 '13 at 12:21

3 Answers3

2

If time is a DateTime, you can simply do something like

TimeSpan ts = new TimeSpan(time.Ticks);
Console.WriteLine(ts.TotalSeconds);

If you want it to work as per your code, then, note the output from ToString() method does not match the string pattern you have provided. Format it to so that the output matches the required pattern, eg,

TimeSpan.ParseExact(time.ToString("mm:ss"), "mm:ss", System.Globalization.CultureInfo.CurrentCulture).TotalSeconds;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kami
  • 19,134
  • 4
  • 51
  • 63
2

Try following:

TimeSpan.ParseExact(time.ToString(), "mm\\:ss", System.Globalization.CultureInfo.CurrentCulture).TotalSeconds;

Read more about Costum TimeSpan Formatting on MSDN

Backslash is as an escape character. This means that, in C#, the format string must either be @-quoted, or mm:ss must be separated by backslash.

Marek
  • 3,555
  • 17
  • 74
  • 123
  • @Ziggy if it was helpful, please mark it as an answer so others can see what was the solution for this issue. Is there anything else we can help you with? – Marek Nov 27 '13 at 12:46
0

According to TimeSpan custom format guide here http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx

You have to sort-of-escape the colon with a backslach, so your format should look like this

TimeSpan.ParseExact(time.ToString(), @"mm\:ss", System.Globalization.CultureInfo.CurrentCulture).TotalSeconds;
Honza Brestan
  • 10,637
  • 2
  • 32
  • 43