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 current century from this date using SimpleDateFormat
?
int century = (year + 99)/ 100;
The other Answers are correct but outdated.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With