我想知道是否有办法从给定的日期字符串中提取 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/