Convert a two digit year to a four digit year

前端 未结 17 970
误落风尘
误落风尘 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: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);
        }
    

提交回复
热议问题