-1

I'm reading data from an excel file. The user can specify the time in one of the following formats:

  • 1600
  • 16:00

In the latter case, I can easily convert it to a timespan. How do I convert the first format to timespan? Is there a straightforward way than manipulating the string to convert to the latter and do it?

devC
  • 1,384
  • 5
  • 32
  • 56
  • 2
    I dunno what's happening with the upvotes that seem to be handed out in the C# tag today mere seconds after questions are asked, but what have you tried? You can specify multiple formats to TryParseExact, for example. – CodeCaster Jun 13 '17 at 11:37
  • `TimeSpan.(Try)ParseExact(input, new string[] { "hhmm", "hh:mm" }, CultureInfo.InvariantCulture)` – Der Kommissar Jun 13 '17 at 11:38

1 Answers1

3

Use

TimeSpan span = TimeSpan.ParseExact("1600", new string[] {"hhmm", @"hh\:mm"}, CultureInfo.InvariantCulture);
adjan
  • 13,371
  • 2
  • 31
  • 48
  • This does not support both formats. – CodeCaster Jun 13 '17 at 11:39
  • 1
    @CodeCaster fixed. Although his question was only about parsing the first string... – adjan Jun 13 '17 at 11:40
  • Because they already knew how to parse the second one. If they had used your previous code, they'd have to parse twice, once for either format. Anyway you now have the same answer as the duplicate question. – CodeCaster Jun 13 '17 at 11:42
  • ```TimeSpan.ParseExact("16:00", new string[] {"hhmm", "hh:mm"}, CultureInfo.InvariantCulture);``` will throw exception – tym32167 Jun 13 '17 at 11:43