Why does TimeSpan.ToString() require escaping separators?

橙三吉。 提交于 2019-11-27 02:41:44

问题


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.


回答1:


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 quiet 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.



来源:https://stackoverflow.com/questions/20924278/why-does-timespan-tostring-require-escaping-separators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!