Issue DateTime.ToString with string format “M” in .NET

落爺英雄遲暮 提交于 2019-12-19 13:49:05

问题


I have a problem with the string format of DateTime. I think it is bug in MS. Can you explain it, and what is wrong?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(DateTime.Now.ToString("M"));//return 07 July   <---- WRONG, SEE MSDN
        Console.WriteLine(DateTime.Now.ToString(".M"));//return .7   <---- GOOD
        Console.ReadKey();
    }
}

MSDN


回答1:


From The "M" Custom Format Specifier

If the "M" format specifier is used without other custom format specifiers, it is interpreted as the "M" standard date and time format specifier. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.

From Using Single Custom Format Specifiers

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they do not recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier "h" is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no "h" standard date and time format specifier.

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

That's why you can use one of these;

Console.WriteLine(DateTime.Now.ToString(" M")); // 7
Console.WriteLine(DateTime.Now.ToString("M ")); //7
Console.WriteLine(DateTime.Now.ToString("%M")); //7


来源:https://stackoverflow.com/questions/24651467/issue-datetime-tostring-with-string-format-m-in-net

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