获取DateTime对象的完整月份名称的正确方法是什么? 1月,12月。
我目前使用:
DateTime.Now.ToString("MMMMMMMMMMMMM");
我知道这不是正确的做法。
获取DateTime对象的完整月份名称的正确方法是什么? 1月,12月。
我目前使用:
DateTime.Now.ToString("MMMMMMMMMMMMM");
我知道这不是正确的做法。
你可以像mservideo建议的那样做,甚至更好,使用这个重载来跟踪你的文化:
DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);
如果你想要当月的,你可以使用 DateTime.Now.ToString("MMMM")获取完整月份或DateTime.Now.ToString("MMM")获取缩写月份。
如果你有其他想要获取月份字符串的日期,在它加载到DateTime对象后,你可以在该对象中使用相同的函数: dt.ToString("MMMM")获取完整的月份,或dt.ToString("MMM")获取缩写的月份。
参考: 自定义日期和时间格式字符串
或者,如果你需要特定文化的月份名称,那么你可以试试这些: DateTimeFormatInfo。GetAbbreviatedMonthName方法 DateTimeFormatInfo。GetMonthName方法
你可以使用文化来获取你国家的月份名称,比如:
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);
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.
*/
如果您接收到“MMMM”作为响应,那么您可能正在获取月份,然后将其转换为定义格式的字符串。
DateTime.Now.Month.ToString("MMMM")
将输出"MMMM"
DateTime.Now.ToString("MMMM")
是否输出月份名称
您可以使用系统中的CultureInfo。全球化来获取数据,基于当前正在使用的文化。
_ = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month)
或者,使用InvariantCulture来获得英文名称。
_ = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);
用这个来表示当月的全名:
DateTime date = DateTime.Now;
string month = $"{date:MMMM}"; // f.g October
用它来做月份的缩写:
DateTime date = DateTime.Now;
string month = $"{date:MMM}"; // f.g Oct
用它来表示本周的全称:
DateTime date = DateTime.Now;
string month = $"{date:dddd}"; // f.g Saturday
用这个作为一周的缩写:
DateTime date = DateTime.Now;
string month = $"{date:ddd}"; // f.g Sat
你可以用这个结构f.g设置每个自定义模板:
DateTime date = DateTime.Now;
string month = $"{date:dd/MMM/yyyy}"; // 12/Oct/2022
string month = $"{date:dd-MM-yyyy}"; // 12-10-2022
string month = $"{date:dd MMMM yyyy}"; // 12 October 2022
string month = $"{date:ddd - - - MMM}"; // Sat - - - Oct
string month = $"{date:ddddd $- yyyy}"; // Saturday $- 2022
string month = $"{date:ddMMyyyy}"; // 12102022