提问人:tinmac 提问时间:9/22/2023 最后编辑:Dmitry Bychenkotinmac 更新时间:9/23/2023 访问量:87
DateTime 格式化 Month,而不考虑区域性?
DateTime formatting Month regardless of culture?
问:
我们是否可以根据用户的窗口文化以以下方式格式化...DateTime
en-GB
= 1st May 2023
en-US
= May 1st 2023
没有通过 或 显式检查和设置每个区域性的格式?CultureInfo
ToString("dd MMM yyy")
ToString("MMM dd yyy")
答:
0赞
Al Mubassir Muin
9/23/2023
#1
您可以使用这些方法来获取您提到的时间格式
static string GetDateTimeWithFormat(DateTime date)
{
string day = date.Day.ToString();
string ordinalIndicator = GetOrdinalIndicator(date.Day);
return date.ToString("MMM") + " " + day + ordinalIndicator + " " + date.Year;
}
// Method to get the ordinal indicator for a day
static string GetOrdinalIndicator(int day)
{
if (day >= 11 && day <= 13)
{
return "th";
}
switch (day % 10)
{
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
评论
0赞
Dmitry Bychenko
9/23/2023
旁注:似乎更具可读性。return $"{date:MMM} {day}{ordinalIndicator} {date.Year}";
1赞
Dmitry Bychenko
9/23/2023
#2
如果我理解正确,您希望检测当前区域性的日和月顺序,然后选择格式字符串(例如,美国区域性)或(对于 GB 区域性)。MMM dd yyy
dd MMM yyy
请注意,某些文化(例如中国)首先使用年份
year month day
格式。如果你坚持年份在末尾,不管文化如何(所以“修改”的中文将是),你可以使用 DateTimeFormat.MonthDayPattern:month day year
private static string MyDateTimeFormatString() =>
CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern[0] == 'M'
? "MMM dd yyy" // Month before day
: "dd MMM yyy"; // Day before month
private static string MyDateTimeFormat(DateTime value) =>
value.ToString(MyDateTimeFormatString());
使用简单
DateTime date = ...
var result = MyDateTimeFormat(date);
所以我们有
en-GB = 01 May 2023 (United Kingdom)
en-US = May 01 2023 (United States)
cn-CN = May 01 2023 (China)
评论
0赞
tinmac
9/23/2023
谢谢你把我介绍给MonthDayPattern
0赞
tinmac
9/23/2023
我不坚持在开头写年份,主要目标不是使用 int 表示月份,而是使用月份名称 3 或完整
0赞
Joel Coehoorn
9/23/2023
#3
您可以使用 .ToShortDateString()
方法或 d
标准格式字符串 ()。.ToString("d")
这两者都具有区域性感知能力,并查看系统设置以了解要显示的格式。
但是,这些选项都不包括使用开箱即用的缩写月份名称或序号日期(带有 、 、 、 )。为此,您需要编写自己的代码。st
nd
rd
th
评论