You can specify a custom format for a DateTime
object like this:
DateTime.Now.ToString("HH:mm:ss"); // 19:55:23
But when I try to use the same format for a TimeSpan
object like this:
DateTime.Now.TimeOfDay.ToString("HH:mm:ss");
I get the "Input string was not in a correct format."
exception.
It turns out, the solution is that you need to escape the ':'
characters like in "HH\\:mm\\:ss"
. Note that there is a double backslash because if you specify only one, it will break the string so you need to escape that one too.
The question is, why .NET Framework developers made it this way? There must be a reason for sure. Why can't we use custom format specifiers without escaping them like we can with a DateTime
object?
Looking for .NET gurus to shed light on this subject.
The .NET Framework does not define a grammar for separators in time intervals.
, I'm not entirely sure what the reasoning is though (worth a read anyway). – Alva