Converting a String to something else can always be tricky. Especially if that String is about time. The thing is the fact that there are many ways to represent time and that can actually depend on the country you are.

6 PM, 6.00 PM, 06.00, 06:00, 18:00, 18h00, 18H00, they could be all the same.

I would say: never use string to represent time! Yes but reality is that sometimes a client might ask you to take an Excel file and get the data from it, which contains some hours in a specific format as a String…

And if you had an exception like this trying to parse the String, you will know what I’m talking about: “System.FormatException: ‘Input string was not in a correct format.’

The key is to use the ParseExact from TimeSpan and use a custom time separator flagged with “\” (but you will need to double it).

TimeSpan time = TimeSpan.ParseExact("18h30", "hh\\hmm", CultureInfo.InvariantCulture);
Code language: C# (cs)

Where “\\h” is here the time separator for 18h30 in “hh\\hmm”.

And that’s where the beauty really starts! If you want to do the same for a DateTime, the format is different…

DateTime time = DateTime.ParseExact("18h30", "HH\\hmm", CultureInfo.InvariantCulture);
Code language: C# (cs)

Yes! If you use the 24 hours format, TimeSpan will use “hh” while DateTime will use “HH“.

Happy coding! 🙂