如何根据当前文化获取仅用数字表示的年月格式模式
获取本地化数字型年月格式的实现方法
要得到随当前文化动态调整、仅用数字展示年月的格式规则,可以通过解析当前文化的短日期模板实现,具体方案如下:
实现逻辑
CultureInfo.DateTimeFormat.ShortDatePattern 本身是符合对应文化使用习惯的数字型年月日格式,仅需要剔除其中的日占位符和多余分隔符,就能得到符合需求的年月格式。
代码示例
using System; using System.Globalization; using System.Text.RegularExpressions; public static string GetNumericYearMonthPattern(CultureInfo targetCulture = null) { // 未指定文化时默认使用当前线程生效的文化 targetCulture ??= CultureInfo.CurrentCulture; string shortDateTemplate = targetCulture.DateTimeFormat.ShortDatePattern; // 移除日的占位符(d/dd)及前后的分隔符 string yearMonthTemplate = Regex.Replace(shortDateTemplate, @"[\/\-\.]?d+[\/\-\.]?", string.Empty).Trim(); // 可选配置:强制月份为两位、年份为四位,按需保留或删除 yearMonthTemplate = yearMonthTemplate.Replace("M", "MM").Replace("y", "yyyy"); return yearMonthTemplate; }
效果验证
直接调用方法得到格式模板后,即可用于DateTime的格式化:
// 示例:测试不同文化下的输出 var testDate = new DateTime(2021,9,1); // 中文(中国)文化 var zhCn = new CultureInfo("zh-CN"); Console.WriteLine(testDate.ToString(GetNumericYearMonthPattern(zhCn), zhCn)); // 输出:2021/09 // 德语(德国)文化 var deDe = new CultureInfo("de-DE"); Console.WriteLine(testDate.ToString(GetNumericYearMonthPattern(deDe), deDe)); // 输出:09.2021 // 英语(美国)文化 var enUs = new CultureInfo("en-US"); Console.WriteLine(testDate.ToString(GetNumericYearMonthPattern(enUs), enUs)); // 输出:09/2021
提示:如果需要保留对应文化原生的单数字月份/年份展示习惯(比如美国地区常见的
9/2021格式),删除代码中强制替换M和y的代码行即可。
内容的提问来源于stack exchange,提问作者Muck
相关产品推荐
相关产品推荐

