Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Century from date in Java

Tags:

java

date

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?

like image 261
Zeeshan Avatar asked Jun 03 '11 15:06

Zeeshan


2 Answers

int century =  (year + 99)/ 100;
like image 180
Chinthaka Devinda Avatar answered Oct 04 '22 15:10

Chinthaka Devinda


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

like image 41
Basil Bourque Avatar answered Oct 04 '22 15:10

Basil Bourque