Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing 2-digit dates [duplicate]

Tags:

c#

.net

datetime

I'm trying to read in a type of file with very old formatting.

In it the date format is specified at being in a yymmdd format, where a 2-digit year in the range [00, 59] is considered to be in the 21st century and a year in the range [60, 99] is considered to be in the 20th century such that 59 represents the year 2059 and 60 represents the year 1960.

How would I go about parsing this into a DateTime in C#?

I've tried doing:

string str = ReadDateFromFile();
DateTime dt;    
DateTime.TryParseExact(str, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

But the default 2-digit year rules treat values in the range [00, 29] as 21st century and values in the range [30, 99] as 20th century.

Is there a way to modify this behaviour to do what I want or is there a different technique I could use?

like image 481
Pharap Avatar asked Dec 31 '15 18:12

Pharap


2 Answers

Just append the century prefix to your string and then change the format string to parse the four digit year

string str = ReadDateFromFile();
if (int.Parse(str.Substring(0, 2) >= 60)
   str = "19" + str;
else
   str = "20" + str;

DateTime dt;    
DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

You can modify Calendar.TwoDigitYearMax and use the modified culture for parsing

var myCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
myCulture.Calendar.TwoDigitYearMax = 2059;
DateTime dt;
DateTime.TryParseExact(str, "yyMMdd", myCulture, DateTimeStyles.None, out dt);
like image 96
Hamid Pourjam Avatar answered Oct 07 '22 21:10

Hamid Pourjam


I think that in this case, it would be easier to use a regular expression such as (\d{2})(\d{2})(\d{2}) to extract the year, month and day respectively, then, you do your business logic and construct a new date time object from there.

If this is a common behaviour in your application, you might want to consider making it an extension method.

like image 45
npinti Avatar answered Oct 07 '22 19:10

npinti