I have to extract datetime pattern from string date.
E.G. I have datetime string "2020.01.01-09:20" I parse this string using culture
var culture = new CultureInfo("en-us");
var date = "2020.01.01-09:20";
var isParsed = DateTime.TryParse(date, culture, DateTimeStyles.AdjustToUniversal, out var result);
Result is correct. Now I have to make some random changes in date and time and parse it back to string with pattern extracted from original string.
I make a method that contains all patterns for culture
private static IList<string> GetDateTimePatterns(CultureInfo culture)
{
var info = culture.DateTimeFormat;
return new string[]
{
info.FullDateTimePattern,
info.LongDatePattern,
info.LongTimePattern,
info.ShortDatePattern,
info.ShortTimePattern,
info.MonthDayPattern,
info.ShortDatePattern + " " + info.LongTimePattern,
info.ShortDatePattern + " " + info.ShortTimePattern,
info.YearMonthPattern,
info.SortableDateTimePattern
};
}
The result of
foreach (var pattern in GetDateTimePatterns(culture))
{
Console.WriteLine(result.ToString(pattern ,culture));
}
generates output:
Wednesday, January 1, 2020 9:20:00 AM
Wednesday, January 1, 2020
9:20:00 AM
1/1/2020
9:20 AM
January 1
1/1/2020 9:20:00 AM
1/1/2020 9:20 AM
January 2020
2020-01-01T09:20:00
As you see there is no pattern that is the same as original string.
How to extract correct pattern depending on culture ?
Aucun commentaire:
Enregistrer un commentaire