c# - 从给定的日期字符串中提取 DateTime 格式

标签 c#

我想知道是否有办法从给定的日期字符串中提取 DateTime 格式。在 C# 中 例如:

var dateString = "12/10/2018";
var format = GetDateFormat(dateString);

然后格式将是“长日期时间”之类的。

最佳答案

通过硬编码或反射(如下所示),您可以检索所有 properties of the DateTimeFormatInfo class 的值其名称以 "Pattern" 结尾,然后尝试使用这些模式进行解析并查看哪些成功。不过,您将受限于该类提供的模式以及您选择使用的任何一种或多种文化。

DateTimeFormatInfo formatInfo = DateTimeFormatInfo.CurrentInfo;
IEnumerable<PropertyInfo> patternProperties = formatInfo.GetType().GetProperties()
    .Where(property => property.Name.EndsWith("Pattern"));

foreach (PropertyInfo patternProperty in patternProperties)
{
    string pattern = (string) patternProperty.GetValue(formatInfo);
    bool wasParsed = DateTime.TryParseExact(dateString, pattern, formatInfo, DateTimeStyles.None, out DateTime _);

    Console.WriteLine($"{patternProperty.Name} (\"{pattern}\"): {wasParsed}");
}

在我的系统 (en-US) 上,上述代码产生以下输出:

FullDateTimePattern ("dddd, MMMM d, yyyy h:mm:ss tt"): False
LongDatePattern ("dddd, MMMM d, yyyy"): False
LongTimePattern ("h:mm:ss tt"): False
MonthDayPattern ("MMMM d"): False
RFC1123Pattern ("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"): False
ShortDatePattern ("M/d/yyyy"): True
ShortTimePattern ("h:mm tt"): False
SortableDateTimePattern ("yyyy'-'MM'-'dd'T'HH':'mm':'ss"): False
UniversalSortableDateTimePattern ("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"): False
YearMonthPattern ("MMMM yyyy"): False

关于c# - 从给定的日期字符串中提取 DateTime 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50457694/

相关文章:

c# - .NET 浏览器模拟 API

c# - 我的对象在哪里被处置?

c# - MVC 4's mapRoute URL -- {controller}/{action} vs Controller/{action}. What' 的区别?

c# - 字段更改时,MVVM 对象触发属性更改事件

c# - FileSystemWatcher Changed 事件不会针对内存映射文件触发

c# - DLL基地址

c# - 在 C# 中实现三角反函数

c# - 嵌套调用中的异步和等待。不等待执行等待导致 IIS 崩溃的方法

c# - Windows ML 学习模型是否可以通过 UWP 之外的 C# 访问?

c# - 获取 Dictionary 中包含值 x 的所有键