How to make DateTime.TryParse() fail if no year is specified?

前端 未结 3 2219
难免孤独
难免孤独 2021-02-10 13:48

Consider the following code to parse a date. (Note that I\'m in the EN-gb locale):

const DateTimeStyles DATE_TIME_STYLES = DateTimeStyles.NoCurrentDateDefault |          


        
3条回答
  •  忘掉有多难
    2021-02-10 14:32

    You could query for the culture's patterns, filter out those without a year and then use TryParseExact on the remaining patterns.

    var allPatterns = culture.DateTimeFormat.GetAllDateTimePatterns();
    var patternsWithYear = allPatterns.Where(s => s.Contains("y")).ToArray();
    bool success = TryParseExact(input, patternsWithYear, culture, styles, out dateTime);
    

    Known bug: This doesn't take escaping into account, you'll need to replace the Contains("y") call with proper parsing to fix this.

    Alternatively you could go with just LongDatePattern and ShortDatePattern if you're fine with stricter format constraints.

提交回复
热议问题