问题DateTime.ToString与字符串格式“M”在.NET中 [英] Issue DateTime.ToString with string format "M" in .NET
问题描述
我对DateTime的字符串格式有问题。我认为这是MS的错误。你可以解释一下,什么是错的?
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();
}
}
推荐答案
From The "M"
Custom Format Specifier
如果没有其他自定义使用M格式说明符格式
说明符,它被解释为M
标准日期和时间格式
说明符。有关使用单个格式说明符的详细信息,请参阅使用单个自定义格式说明符 a>本主题后面。
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.
自定义日期和时间格式字符串由两个或更多
个字符。日期和时间格式化方法将任何
单字符字符串解释为标准日期和时间格式字符串。如果
,他们不会将该字符识别为有效的格式说明符,则
抛出一个FormatException
。 例如,只有说明符h的
的格式字符串被解释为标准日期和时间
格式字符串。然而,在这种特殊情况下,抛出一个例外是
,因为没有h标准日期和时间格式
说明符。
要使用任何自定义日期和时间格式说明符作为格式字符串中唯一的
说明符(即使用d,f,F,g,
h,H,K,m,M,s,t,y,z,: /自定义格式
说明符本身),在说明符之前或之后包含空格,
或在单个自定义
日期之前包含百分比(%)格式说明符和时间说明符。
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
这篇关于问题DateTime.ToString与字符串格式“M”在.NET中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!