You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多语言应用中按文化结构用缩写月份格式化DateTime

解决多语言场景下DateTime的缩写月日格式化问题

核心思路

直接复用目标文化内置的月日格式模板,仅将其中的完整月份占位符替换为缩写月份占位符,既能保留该文化固有的格式结构(月日顺序、标点符号等),又能满足月份缩写的需求。

具体实现

每个文化的DateTimeFormatInfo.MonthDayPattern属性,对应了该文化下ToString("m")使用的标准月日格式模板。我们只需要把模板中的MMMM(完整月份标识)替换为MMM(缩写月份标识),再用这个自定义模板格式化DateTime对象即可。

代码示例:

// 针对当前线程默认文化的格式化
var currentCulture = CultureInfo.CurrentCulture;
var customPattern = currentCulture.DateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM");
string formattedDate = DateTime.Now.ToString(customPattern, currentCulture);

// 针对特定文化的示例(以挪威语为例)
var norwegianCulture = new CultureInfo("nb-NO");
var norwegianPattern = norwegianCulture.DateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM");
string norwegianFormattedDate = DateTime.Now.ToString(norwegianPattern, norwegianCulture);

方法优势

  • 完全遵循不同文化的内置格式规则:比如英语(美国)会输出Oct 12,挪威语会输出12. okt,无需手动硬编码任何格式结构。
  • 适配所有.NET支持的文化,扩展性强,不会出现强制固定月日顺序的问题。

内容的提问来源于stack exchange,提问作者Fredrik Giertsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:25:32