Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

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;

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top