How to get Century from date in Java

前端 未结 5 945
孤独总比滥情好
孤独总比滥情好 2021-01-04 20:41

How to get current Century from a date in Java?

For example the date \"06/03/2011\" according to format \"MM/dd/yyyy\". How can I get curre

5条回答
  •  盖世英雄少女心
    2021-01-04 21:16

    The other Answers are correct but outdated.

    java.time

    The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    Now in maintenance mode, the Joda-Time project also advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

    LocalDate

    The LocalDate class represents a date-only value without time-of-day and without time zone.

    To parse specify a formatting pattern. By the way, I suggest using ISO 8601 standard formats which can be parsed directly by java.time classes.

    String input = "06/03/2011";
    
    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu" ).withLocale ( Locale.US );
    LocalDate ld = LocalDate.parse ( input , f );
    

    To get the century, just take the year number and divide by 100. If you want the ordinal number, "twenty-first century" for 20xx, add one.

    int centuryPart = ( ld.getYear () / 100 );
    int centuryOrdinal = ( ( ld.getYear () / 100 ) + 1 );
    

    Dump to console.

    System.out.println ( "input: " + input + " | ld: " + ld + " | centuryPart: " + centuryPart + " | centuryOrdinal: " + centuryOrdinal );
    

    input: 06/03/2011 | ld: 2011-06-03 | centuryPart: 20 | centuryOrdinal: 21

提交回复
热议问题