gpt4 book ai didi

c# - 在 .NET 中使用字符串格式 "M"发出 DateTime.ToString

转载 作者:可可西里 更新时间:2023-11-01 08:36:26 28 4
gpt4 key购买 nike

我对 DateTime 的字符串格式有疑问。我认为这是 MS 中的错误。你能解释一下吗?有什么问题吗?

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

最佳答案

来自 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.

来自 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.

这就是您可以使用其中之一的原因;

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

关于c# - 在 .NET 中使用字符串格式 "M"发出 DateTime.ToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24651467/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com