Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...