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

前端 未结 3 1963
心在旅途
心在旅途 2021-02-10 14:14

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:23

    The more I think about this the more I think it's a bad solution but given you're getting no other answers I'll post it anyway.

    DateTime temp;
    DateTime.TryParse(input, CultureInfo.CurrentUICulture, DATE_TIME_STYLES, out temp);
    
    if (temp.Year == DateTime.Now.Year)
    {
        if (!input.Contains(DateTime.Now.Year))
        {
            if (temp.Days != int.Parse(DateTime.Now.Year.ToString().SubString(2)))
            {
                 // my god that's gross but it tells you if the day is equal to the last two
                 // digits of the current year, if that's the case make sure that value occurs
                 // twice, if it doesn't then we know that no year was specified
            } 
        }
    }
    

    Also, as others have suggested in comments now, checking the number of tokens or the strings length could also be useful like;

    char[] delims = new char[] { '/', '\', '-', ' '); //are there really any others?
    bool yearFound = false;
    
    foreach (char delim in delims)
    {
        if (input.Split(delim).Count == 3)
        {
             yearFound = true;
             break;
        }
    }
    
    if (yearFound)
        //parse
    else
        // error
    

    These are just a couple of ideas, neither is truly sound. They're obviously both hacks, only you can know if they'll suffice. At least they beat your co-workers if (dt.Year == 2014) //discard input "solution".

    0 讨论(0)
  • 2021-02-10 14:26

    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.

    0 讨论(0)
  • 2021-02-10 14:39

    You can use parse exact like this and catch the exception.

    CurrentUICulture.DateTimeFormat.ShortDatePattern will give you the cultures short date pattern.

    There is also DateTime.TryParseExact

    DateTime.ParseExact(value.ToString(), cultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToString, cultureInfo.CurrentUICulture)
    
    0 讨论(0)
提交回复
热议问题