0

I try to parse string via c#:

  var tm = TimeSpan.ParseExact(00:00.00000, "hh:mm.sssss", CultureInfo.InvariantCulture);

and then get TotalMilliseconds, but i get FormatException.

How to do that?

Admiral Land
  • 2,304
  • 7
  • 43
  • 81
  • That *is* an invalid format. You can't have 5 second digits. – Panagiotis Kanavos Nov 15 '18 at 10:52
  • @PanagiotisKanavos, and if it is milliseconds? – Admiral Land Nov 15 '18 at 10:53
  • @AdmiralLand Then you would do `hh:mm.ss.fff` Your time parameter needs to change too.. `00:00.00000` should become `00:00.00.000` – Adrian Nov 15 '18 at 10:54
  • Post what you actually want to do. Do you *really* have a string containing only minuetes and seconds? No hours? The snippet you posted here won't even compile – Panagiotis Kanavos Nov 15 '18 at 10:55
  • 1
    Looks like `@"mm\:ss\.fffff"`, but with only zeroes it's hard to tell. – Jeroen Mostert Nov 15 '18 at 10:55
  • `TimeSpan.ParseExact("00:00.00000", "mm\\:ss\\.fffff", CultureInfo.InvariantCulture)` will work. As the duplicate question and [the documentation](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings#other-characters) shows, any character that isn't a format specifier, including separators, needs escaping – Panagiotis Kanavos Nov 15 '18 at 10:58
  • 1
    That's not an arbitrary restriction either. The format patterns are the same for formatting and parsing. `:` is used to separate arguments from format strings. The same pattern can be used in `String.Format("{0:mm\\:ss\\.fffff}", TimeSpan.Zero)`. This would break if `:` wasn't escaped – Panagiotis Kanavos Nov 15 '18 at 11:03
  • @JeroenMostert, i have log file with timestamp:00:00.05601 , and it is mm:ss:milliseconds – Admiral Land Nov 15 '18 at 11:06
  • @JeroenMostert, i solve it by parse 00000 as milliseconds and 00:00 as mm\\:ss. And then sum it. – Admiral Land Nov 15 '18 at 11:16
  • var ts = TimeSpan.ParseExact(val, "mm\\:ss\\.fffff", CultureInfo.InvariantCulture); – Admiral Land Nov 15 '18 at 11:58

0 Answers0