Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does TimeSpan.ToString() require escaping separators?

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.

like image 752
anar khalilov Avatar asked Jan 04 '14 17:01

anar khalilov


1 Answers

As stated in documentation, one of the differences between DateTime.ToString and TimeSpan.ToString format specifiers is the following: the custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.

In contrast with TimeSpan (see table of format specifiers in docs), DateTime format specifiers include predefined symbols for Date separator /, and for Time separator :. It means that for example for Italian culture semicolon will be recognized as time separator (not the literal) and will be replaced with . symbol:

    // outputs 09.57.18 instead of 09:57:18 because of Italian culture.
    Console.WriteLine(DateTime.Now.ToString("hh:mm:ss", CultureInfo.GetCultureInfo("it-IT")));

I think .NET designers made such difference between DateTime and TimeSpan string formatters intentionally, and it is quite reasonable. This is because historically Date/Time were formatted differently for different cultures. And .NET tried to provide globalization means for that matter along with DateTime type. But TimeSpan did not get such 'globalization' duties, it is just a type representing period of time, and formatting of it is not tied to any culture specifics (if they are ever existed), but instead formatting of it is constant in different culture settings.

like image 71
SergeyS Avatar answered Oct 05 '22 19:10

SergeyS