Other answers are correct but outdated.
java.time
The java.time framework is built into Java 8 and later. These classes supersede old inconvenient time classes such as java.util.Date , .Calendar and java.text.SimpleDateFormat .
Now, in Joda-Time maintenance mode, the project also advises switching to java.time.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations.
Most of the functionality of java.time is ported to Java 6 and 7 in ThreeTen-Backport and further adapted for Android in ThreeTenABP .
The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time.
LocalDate
The LocalDate class represents a date value only without time and without a time zone.
To parse, specify a formatting template. By the way, I suggest using standard ISO 8601 formats, which can be analyzed directly by the 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 a century, just take the year number and divide it by 100. If you want a serial number , "twenty first century", for 20xx add one.
int centuryPart = ( ld.getYear () / 100 ); int centuryOrdinal = ( ( ld.getYear () / 100 ) + 1 );
Dump for the console.
System.out.println ( "input: " + input + " | ld: " + ld + " | centuryPart: " + centuryPart + " | centuryOrdinal: " + centuryOrdinal );
entry: 03/03/2011 | ld: 2011-06-03 | centuryPart: 20 | centuryOrdinal: 21
Basil bourque
source share