I would like to be able to get the format string from a DateTime string.
e.g.
"2012-12-08 15:00:00" => "yyyy-MM
I had the same idea as Jon Skeet and went to implement it:
// Helper method
IEnumerable DateTimeFormatPatterns(DateTimeFormatInfo format)
{
var accessors = new Func[]
{
f => f.FullDateTimePattern,
f => f.LongDatePattern,
f => f.LongTimePattern,
f => f.MonthDayPattern,
f => f.ShortDatePattern,
f => f.SortableDateTimePattern,
f => f.UniversalSortableDateTimePattern,
f => f.YearMonthPattern,
};
return accessors.Select(accessor => accessor(format));
}
// The real function
string DetectDateTimeFormat(string date, CultureInfo culture)
{
DateTime dummy;
foreach (var pattern in DateTimeFormatPatterns(culture.DateTimeFormat))
{
if (DateTime.TryParseExact(date, pattern, culture,
DateTimeStyles.None, out dummy))
{
return pattern;
}
}
return null;
}
There is space for improvement here (e.g. the hardcoded DateTimeStyles.None doesn't help, an overload which assumes the current culture would also be useful), but you can use it like this:
var format = DetectDateTimeFormat("2012-12-08 15:00:00",
CultureInfo.CurrentCulture);