DateTime.ParseExact for non-traditional years

I am trying to read dates in the following format using a single format string:

"1000.12.31"
"999.12.31"
"99.12.31"

They corresponded to dates in 1000 A.D., 999 A.D. and 99 A.D.

I tried the following format lines:

yyyy.M.d. This fails for 999 and 99 years.

yy.M.d. This fails for 1000 and 999. It also interprets 99 as 1999.

I'm going to resort to parsing it manually (simple enough for this), but I'm wondering if something like this is DateTime.ParseExactpossible with, or possibly with, another built-in method?

+2
source share
3 answers

This is trivial for manual parsing; I don’t think it is worth the effort trying to adapt it to work with DateTime.ParseExact.

string str = "99.12.31";
int[] parts = str.Split('.').Select(int.Parse).ToArray();
DateTime date = new DateTime(parts[0], parts[1], parts[2]);
+2

, - , DateTime.ParseExact.

, DateTime.ParseExact.

static DateTime ParseExactYear(string input)
{
    switch (input.IndexOf('.'))
    {
        case 1: input = "000" + input; break;
        case 2: input = "00" + input; break;
        case 3: input = "0" + input; break;
    }

    return DateTime.ParseExact(input, "yyyy.M.d", null);
}

Debug.WriteLine(ParseExactYear("1000.12.31"));
Debug.WriteLine(ParseExactYear("999.12.31"));
Debug.WriteLine(ParseExactYear("99.12.31"));
Debug.WriteLine(ParseExactYear("9.12.31"));

Debug.WriteLine(ParseExactYear("1000.1.1"));
Debug.WriteLine(ParseExactYear("999.1.1"));
Debug.WriteLine(ParseExactYear("99.1.1"));
Debug.WriteLine(ParseExactYear("9.1.1"));

Output:
12/31/1000 12:00:00 AM
12/31/0999 12:00:00 AM
12/31/0099 12:00:00 AM
12/31/0009 12:00:00 AM
1/1/1000 12:00:00 AM
1/1/0999 12:00:00 AM
1/1/0099 12:00:00 AM
1/1/0009 12:00:00 AM
+2

99 1999 - DateTimeFormatInfo. , DateTimeFormatInfo:

string eg = "9.1.2";
DateTime dt;

var fi = new System.Globalization.DateTimeFormatInfo();
fi.Calendar = (System.Globalization.Calendar)fi.Calendar.Clone();
fi.Calendar.TwoDigitYearMax = 99;
fi.ShortDatePattern = "y.M.d";
bool b = DateTime.TryParse(eg, fi, System.Globalization.DateTimeStyles.None, out dt);

DateTimeFormatInfo Calendar; Clone , .

+2

All Articles