Convert a two digit year to a four digit year

前端 未结 17 984
误落风尘
误落风尘 2020-12-25 12:13

This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do <

17条回答
  •  我在风中等你
    2020-12-25 12:46

    You can also use the DateTime.TryParse method to convert your date. It uses the current culture settings to define the pivot year (in my case it is 2029)

    DateTime resultDate;
    Console.WriteLine("CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : {0}", System.Globalization.CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax);
    DateTime.TryParse("01/01/28", out resultDate);
    Console.WriteLine("Generated date with year=28 - {0}",resultDate);
    DateTime.TryParse("01/02/29",out resultDate);
    Console.WriteLine("Generated date with year=29 - {0}", resultDate);
    DateTime.TryParse("01/03/30", out resultDate);
    Console.WriteLine("Generated date with year=30 - {0}", resultDate);
    

    The output is:

    CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : 2029

    Generated date with year=28 - 01/01/2028 00:00:00

    Generated date with year=29 - 01/02/2029 00:00:00

    Generated date with year=30 - 01/03/1930 00:00:00

    If you want to change the behavior you can create a culture with the year you want to use as pivot. This thread shows an example

    DateTime.TryParse century control C#

    But as martin stated, if you want to manage a time period that spans more than 100 year, there is no way to do it with only 2 digits.

提交回复
热议问题