如何从DateTime获取完整的月份名称

160 c# datetime calendar

获取DateTime对象月份的完整名称的正确方法是什么?
例如January,December.

我目前正在使用:

DateTime.Now.ToString("MMMMMMMMMMMMM");
Run Code Online (Sandbox Code Playgroud)

我知道这不是正确的做法.

mse*_*dio 259

使用"MMMM"自定义格式说明符:

DateTime.Now.ToString("MMMM");
Run Code Online (Sandbox Code Playgroud)

  • 令人惊讶的是我得到的文字"MMMM" (5认同)
  • 如果它只是你感兴趣的那个月,那么DateTime.Today而不是DateTime.Now是一个进一步的简化.没有无用的时间部分,也有点快. (3认同)

emp*_*emp 82

您可以像mservidio建议的那样,甚至更好地使用此重载来跟踪您的文化:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

  • 太好了,我需要研究这种文化内容。 (3认同)
  • 如果它只是您感兴趣的月份,那么 DateTime.Today 而不是 DateTime.Now 是进一步的简化。没有无用的时间部分,速度更快。 (2认同)

Jef*_*ake 38

如果您想要当前月份,您可以使用它 DateTime.Now.ToString("MMMM")来获得整月或DateTime.Now.ToString("MMM")获得缩写月份.

如果您有其他日期要获取月份字符串,则在将其加载到DateTime对象后,您可以使用该对象的相同功能:
dt.ToString("MMMM")获取整月或dt.ToString("MMM")获得缩写月份.

参考: 自定义日期和时间格式字符串

或者,如果您需要特定于文化的月份名称,则可以尝试以下操作: DateTimeFormatInfo.GetAbbreviatedMonthName方法
DateTimeFormatInfo.GetMonthName方法


Ale*_*pin 14

它的

DateTime.Now.ToString("MMMM");
Run Code Online (Sandbox Code Playgroud)

4 M秒.


Yeh*_*hia 14

您可以使用Culture来获取您所在国家/地区的月份名称,例如:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);
Run Code Online (Sandbox Code Playgroud)


Ste*_*n H 11

它应该是公正的 DateTime.ToString( "MMMM" )

你不需要所有额外M的东西.


小智 8

如果收到“ MMMM”作为响应,则可能是在获取月份,然后将其转换为定义格式的字符串。

DateTime.Now.Month.ToString("MMMM") 
Run Code Online (Sandbox Code Playgroud)

将输出“ MMMM”

DateTime.Now.ToString("MMMM") 
Run Code Online (Sandbox Code Playgroud)

将输出月份名称


Mad*_*ite 6

DateTime birthDate = new DateTime(1981, 8, 9);
Console.WriteLine ("I was born on the {0}. of {1}, {2}.", birthDate.Day, birthDate.ToString("MMMM"), birthDate.Year);

/* The above code will say:
"I was born on the 9. of august, 1981."

"dd" converts to the day (01 thru 31).
"ddd" converts to 3-letter name of day (e.g. mon).
"dddd" converts to full name of day (e.g. monday).
"MMM" converts to 3-letter name of month (e.g. aug).
"MMMM" converts to full name of month (e.g. august).
"yyyy" converts to year.
*/
Run Code Online (Sandbox Code Playgroud)