Convert a two digit year to a four digit year

前端 未结 17 881
误落风尘
误落风尘 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:33
     int fYear = Convert.ToInt32(txtYear.Value.ToString().Substring(2, 2));
    
    0 讨论(0)
  • 2020-12-25 12:35

    Given that there are people alive now born before 1950, but none born after 2010, your use of 50 as the flipping point seems broken.

    For date of birth, can you not set the flip point to the 'year of now' (i.e. 10) in your app? Even then you'll have problems with those born before 1911...

    There's no perfect way to do this - you're creating information out of thin air.

    I've assumed DOB = date-of-birth. For other data (say, maturity of a financial instrument) the choice might be different, but just as imperfect.

    0 讨论(0)
  • 2020-12-25 12:38

    To change a 2-digit year to 4-digit current or earlier -

    year = year + (DateTime.Today.Year - DateTime.Today.Year%100);
    if (year > DateTime.Today.Year)
                    year = year - 100;
    
    0 讨论(0)
  • 2020-12-25 12:41

    Based on above solutions, here is mine, i used in android while using java

    it takes current year in two digit format then checks for if input year length is equal to 2, if yes then it get current year and from this year it splits first two digits of century, then it adds this century with year user input. to make it 4 digit year.

    public static int getConvertedYearFromTwoToFourDigits(String year) {
            if (year.length() == 2) {
                int currentYear = Calendar.getInstance().get(Calendar.YEAR);
                String firstTwoDigitsOfCurrentYear = String.valueOf(currentYear).substring(0, 2);
                year = firstTwoDigitsOfCurrentYear + year;
            }
            return Integer.parseInt(year);
        }
    
    0 讨论(0)
  • 2020-12-25 12:42

    It might be smarter to check tmpYear > currentYear%100. If it is, then it's 19XX, otherwise 20XX.

    0 讨论(0)
  • 2020-12-25 12:43

    I think Java has a good implementation of this:

    http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year

    People rarely specify years far into the future using a two-digit code. The Java implementation handles this by assuming a range of 80 years behind and 20 years ahead of the current year. So right now, 30 would be 2030, while 31 would be 1931. Additionally, this implementation is flexible, modifying its ranges as time goes on, so that you don't have to change the code every decade or so.

    I just tested, and Excel also uses these same rules for 2-digit year conversion. 1/1/29 turns into 1/1/2029. 1/1/30 turns into 1/1/1930.

    0 讨论(0)
提交回复
热议问题