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

前端 未结 3 1972
心在旅途
心在旅途 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".

提交回复
热议问题