Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for valid Date in yyyyMM format

Tags:

string

date

c#

.net

I have an internal business process that my finance dept runs. To kick it off they input a Date in the format of yyyyMM or 201009. I want to check for a valid date from that string but so far I got nothing.

I am currently exploring breaking the string up, taking the first 4 and checking that they are between 1990 and 2050(as example) and then the last 2 and checking that it is between 01 and 12.

Is there a better way?

like image 479
Refracted Paladin Avatar asked Dec 02 '22 05:12

Refracted Paladin


1 Answers

You can use DateTime.TryParseExact to see if it can be parsed correctly:

bool isValid = false;
DateTime dateValue;
if(DateTime.TryParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, out dateValue))
{
   // DateTime parsed, dateValue contains the parsed DateTime

   // Can validate dateValue against business rules at this point
   isValid = (dateValue <= DateTime.Now && dateValue >= DateTime.Now.AddYears(-5));
}

If you would rather get an exception, you can use DateTime.ParseExact:

// Next line throws exception if format not correct
DateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture);
like image 55
Oded Avatar answered Dec 04 '22 09:12

Oded