How to convert two digit year to full year using Java 8 time API

前端 未结 5 1036
渐次进展
渐次进展 2021-01-17 17:41

I wish to remove the Joda-Time library from my project.

I am trying to convert a two digit year to full year. The following code from Joda-Time can fulfil the purpos

5条回答
  •  囚心锁ツ
    2021-01-17 18:28

    You could parse the year directly using formatter.parse(input, Year::from) :

    import java.time.*;
    import java.time.format.*;
    class Main {
      public static void main(String[] args) {
        DateTimeFormatter TWO_YEAR_FORMATTER = DateTimeFormatter.ofPattern("yy");
        Year year = TWO_YEAR_FORMATTER.parse("99", Year::from);
        System.out.println(year);
      }
    }
    

    Note that this will output 2099. To output 1999, you should use a specific formatter like the one suggested by Ole V.V. in their answer.

提交回复
热议问题