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

Consider the following code for parsing a date. (Note that I'm on the EN-gb locale):

const DateTimeStyles DATE_TIME_STYLES = DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces;
DateTime dt;

// Current culture for this example is "EN-gb".

if (DateTime.TryParse("31/12", CultureInfo.CurrentUICulture, DATE_TIME_STYLES, out dt))
    Console.WriteLine("Parsed correctly"); // Do not want!
else
    Console.WriteLine("Did not parse correctly.");

I intentionally omit the year. However, it TryParse()will analyze this without any errors and will replace the current year.

I would like to force the user to enter ALL date components (using their local format), so I would like the parsing described above to fail, or to detect that the user didn not enter the year.

I really don't want to use it DateTime.TryParseExact(), because then I will need to add code to indicate all the different valid formats for all supported locales, which is non-trivial and likely error prone. I suspect this may be my only reasonable option.

Does anyone have any ideas? (Someone here at work has already implemented a “solution”, which implies the impossibility of the current year, which is clearly not a good solution ...)

+4
source share
3 answers

You can request culture patterns, filter them out without a year, and then use them TryParseExacton 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);

: , Contains("y") , .

LongDatePattern ShortDatePattern, .

+3

.

CurrentUICulture.DateTimeFormat.ShortDatePattern .

DateTime.TryParseExact

DateTime.ParseExact(value.ToString(), cultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToString, cultureInfo.CurrentUICulture)
+3

, , , , .

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 gross but it tells you if the day is equal to the last two
             // digits of the current year, if that the case make sure that value occurs
             // twice, if it doesn't then we know that no year was specified
        } 
    }
}

, , , :

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

, . , , , . , if (dt.Year == 2014) //discard input "".

+2

Source: https://habr.com/ru/post/1532327/


All Articles