Introduction
The getEra() method in the LocalDate class is used to get the era of a date. The IsoChronology class defines eras CE (Current Era) from year one onwards and BCE (Before Current Era) from year zero backward. This method does not take any arguments and returns an IsoEra enum value.
Create a new Java class in the project directory
We will create a new Java class in the project directory named DateEraExample.java. First, navigate to the project directory.
cd ~/project
Now create a new file named DateEraExample.java using the nano editor.
touch DateEraExample.java
Implement the Java code to demonstrate the getEra() method
In the DateEraExample.java file, we will create a Java program to demonstrate the getEra() method in the LocalDate class.
import java.time.LocalDate;
import java.time.chrono.IsoEra;
public class DateEraExample {
public static void main(String[] args) {
// Creating a date with year 2021
LocalDate localDate = LocalDate.of(2021, 11, 10);
// Printing the date
System.out.println("Date: " + localDate);
// Getting the era of the specified date
IsoEra era = localDate.getEra();
// Printing the era
System.out.println("Era: " + era);
// Creating a date with year 0
LocalDate zeroDate = LocalDate.of(0, 1, 1);
// Printing the date
System.out.println("Date with year zero: " + zeroDate);
// Getting the era of the specified date
era = zeroDate.getEra();
// Printing the era
System.out.println("Era: " + era);
}
}
Compile and run the Java program
Save the changes to the DateEraExample.java file and exit the editor. Now compile the Java program using the following command in the terminal.
javac DateEraExample.java
After compiling the program, execute the program using the following command.
java DateEraExample
The output of the program should be displayed on the terminal.
Date: 2021-11-10
Era: CE
Date with year zero: 0000-01-01
Era: BCE
Summary
In this lab, we learned how to use the getEra() method in the LocalDate class of Java to get the era of a date. The IsoChronology class defines eras CE (Current Era) from year one onwards and BCE (Before Current Era) from year zero backward. This method returns an IsoEra enum value representing the era of the date.



