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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With