[英]How to get DateTime Format String of actual date-time?
我想要一個日期時間字符串,並獲取其格式的字符串版本:
例如,如果由於解析異常而錯誤地解析了日期時間,那么2017-01-02
將產生YYYY-MM-dd
以便記錄。
System.DateTime
或任何其他內置功能是否可能?
“ 2017-01-02”將產生“ YYYY-MM-dd”
這是不可能的。 您所要求的魔力 ,使無中生有 。
沒有元信息,計算機(或人類)無法決定是1月2日還是2月1日。 兩者都有可能。
沒有可靠的方法來獲取基於看起來像日期的字符串的格式字符串。
我能想到的最接近的技巧是遍歷所有區域性,然后嘗試ParseExact在每個culturinfo的DateTimeFormat屬性中找到的預定義DateTime模式。
黑客看起來像這樣:
var date = "2017-01-02";
var formats = new Dictionary<string,int>();
// go over all cultures
foreach(var ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
// each culture has a DateTimeFormatInfo that holds date and time patterns
foreach(var p in typeof(DateTimeFormatInfo)
.GetProperties()
.Where(prop => prop.Name.EndsWith("Pattern")))
{
// get a pattern property from the cultureinfo DateTimeFormat
var fmt = (string) p.GetValue(ci.DateTimeFormat, null);
try
{
// try to parse the date
DateTime.ParseExact(date,fmt , ci);
// add the format
if (formats.Keys.Contains(fmt))
{
formats[fmt]++; // how often this was a valid date
}
else
{
formats.Add(fmt, 1); // first time we found it
}
}
catch
{
// no date in this culture for this format, ignore
}
}
}
// output the formats that were parsed as a date
foreach(var kv in formats)
{
// Dump is a linqPad extension, use Console.WriteLine if that bothers you
kv.Value.Dump(kv.Key);
}
然后在我的盒子上返回
yyyy-MM-dd
40
yyyy-Md
1個
現在,對於01/02/2017
它將返回:
dd / MM / yyyy
255d / M / yyyy
93M / d / yyyy
20d / MM / yyyy
11MM / dd / yyyy
2
其中顯示了評論中提出的一些擔憂。 不知道文化是如何生成日期字符串的,就只能猜測日期格式是什么。 最壞的情況是字符串之間帶有數字和破折號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.