How to check the actual date in yyyyMM format

I have an internal business process that runs my financial department. To drop it, they enter a date in yyyyMM or 201009 format. I want to check the valid date from this line, but haven’t received anything yet.

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

Is there a better way?

+4
source share
5 answers

You can use DateTime.TryParseExact to make sure 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 prefer to get an exception, you can use DateTime.ParseExact :

 // Next line throws exception if format not correct DateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture); 
+14
source

You can use regex:

 if (Regex.IsMatch(input, @"^(199\d|20[0-5]\d)(0[1-9]|1[0-2])$")) { // valid input between 199001 and 205912 } 
+4
source

I would go with DateTime.ParseExact:

 DateTime d = DateTime.ParseExact("201009", "yyyyMM", System.Globalization.CultureInfo.InvariantCulture); 
+1
source

The problem here is that the format "yyyyMM" cannot represent a specific DateTime . Therefore, parsing methods built in DateTime will not help you.

Update : it doesn’t matter; I stand fixed. DateTime.TryParseExact will work just fine (which is ironic if you ask me); it will interpret your string to represent the first day of a given month.

I would do what you describe: by analyzing a string in two numeric components and simply comparing these values ​​with any range that you need so that they fall inside.

0
source

I will be tempted to do this as a problem with a number of numbers:

 UInt32 val; if (input.Length != 6 || !UInt32.TryParse(input, out val) || val > 205012 || val < 199001 || val % 100 > 12 || val % 100 == 0) { // Invalid... } 
0
source

All Articles