如何在C#中从给定日期字符串提取DateTime格式?
在C#中从日期字符串识别标准日期格式标识
首先得说清楚:这个需求有点 tricky,因为同一个日期字符串可能对应多种标准格式(比如"12/10/2018"在美式英语里是短日期格式,在英式英语里也可能是短日期格式,只是日和月的顺序反了),而且你要的是“长日期时间”这类标准格式标识,不是自定义的格式字符串(比如MM/dd/yyyy)。
下面是一个可行的实现思路和代码:
实现步骤
- 先把输入的日期字符串解析成
DateTime对象,确保它是有效的日期值。 - 预定义系统里的标准格式标识(比如
"d"对应短日期,"D"对应长日期等)和它们对应的友好名称。 - 将解析后的
DateTime用每个标准格式转换成字符串,和原输入字符串对比,找到匹配的格式标识。
代码示例
using System; using System.Globalization; using System.Collections.Generic; public static class DateFormatDetector { // 定义标准格式标识和对应的友好名称 private static readonly Dictionary<string, string> _standardFormatNames = new Dictionary<string, string> { {"d", "短日期"}, {"D", "长日期"}, {"f", "完整日期/时间(短时间)"}, {"F", "完整日期/时间(长时间)"}, {"g", "常规日期/时间(短时间)"}, {"G", "常规日期/时间(长时间)"}, {"m", "月/日"}, {"M", "月/日"}, {"o", "往返日期/时间"}, {"O", "往返日期/时间"}, {"s", "可排序日期/时间"}, {"t", "短时间"}, {"T", "长时间"}, {"u", "通用可排序日期/时间"}, {"U", "通用完整日期/时间"}, {"y", "年/月"}, {"Y", "年/月"} }; public static List<string> GetDateFormat(string dateString, CultureInfo culture = null) { culture ??= CultureInfo.CurrentCulture; var matchedFormats = new List<string>(); // 第一步:尝试解析日期字符串 if (!DateTime.TryParse(dateString, culture, DateTimeStyles.None, out DateTime dateValue)) { throw new ArgumentException("输入的不是有效的日期字符串"); } // 第二步:遍历所有标准格式,对比转换后的字符串和原输入 foreach (var formatEntry in _standardFormatNames) { string formattedDate = dateValue.ToString(formatEntry.Key, culture); if (string.Equals(formattedDate, dateString, StringComparison.OrdinalIgnoreCase)) { matchedFormats.Add(formatEntry.Value); } } // 如果没有匹配到标准格式,返回自定义格式提示 if (matchedFormats.Count == 0) { matchedFormats.Add("非标准日期格式(自定义格式)"); } return matchedFormats; } } // 用法示例 class Program { static void Main() { var dateString = "12/10/2018"; // 用美式英语文化(MM/dd/yyyy) var usFormats = DateFormatDetector.GetDateFormat(dateString, new CultureInfo("en-US")); Console.WriteLine("美式英语下匹配的格式:" + string.Join(", ", usFormats)); // 输出:短日期 // 用英式英语文化(dd/MM/yyyy) var gbFormats = DateFormatDetector.GetDateFormat(dateString, new CultureInfo("en-GB")); Console.WriteLine("英式英语下匹配的格式:" + string.Join(", ", gbFormats)); // 输出:短日期 } }
注意事项
- 文化差异:日期格式和区域文化强相关,比如
"12/10/2018"在en-US是10月12日,在en-GB是12月10日,所以解析和匹配时一定要指定正确的CultureInfo,否则结果会出错。 - 多匹配情况:有些日期字符串可能同时匹配多个标准格式,比如
"2018-10-12"可能同时匹配“短日期”和“可排序日期/时间”,这时候方法会返回所有匹配的标识。 - 自定义格式:如果输入的是自定义格式(比如
"12-10-2018"),方法会返回“非标准日期格式(自定义格式)”,你可以根据需求扩展这部分逻辑,比如提取具体的自定义格式字符串。
内容的提问来源于stack exchange,提问作者Daphne
相关产品推荐
相关产品推荐

