Extracting datetime pattern from string based on culture

Viewed 48

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 ?

1 Answers

You appear to be using a custom pattern. You can use infinitely many custom patterns and the environment cannot foresee each and every pattern that you may use. Possible solutions

You may create additional patterns

Since DateTimeFormatInfo is sealed, you may not create a class that inherits from it, but you can create a new class, having some properties of patterns that you may expect.

You may use Levenshtein's distance

Levenshtein's distance is the number of single-character edits that is needed in order to reach string2 starting from string1. You may calculate this distance of your input string for each pattern's version and choose the minimum, as that pattern is the closest.

Related