Parsing the DateTime format to get Format String

前端 未结 4 1534
慢半拍i
慢半拍i 2021-01-03 03:43

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

4条回答
  •  旧巷少年郎
    2021-01-03 04:46

    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);
    

提交回复
热议问题