Get the Japanese era for a Gregorian date

Problem:

You want to know the Japanese era for a Gregorian date.

Solution:

Use a Japanese Calendar and DateFormatSymbols from icu4j to retrieve the Japanese year and era.

//Get a ULocale specifying a locale of Japanese using the Japanese calendar
ULocale jp = new ULocale("en@calendar=japanese");
//Get a calendar instance
Calendar jc = Calendar.getInstance(jp);
//Get a default Gregorian calendar instance
Calendar gc = Calendar.getInstance();
//Set calendar for desired date
gc.set(Calendar.YEAR, 1971);
//The month is zero based
gc.set(Calendar.MONTH, 9);
gc.set(Calendar.DATE, 22);
//Set the Japanese calendar using your Gregorian calendar
jc.setTimeInMillis(gc.getTimeInMillis());
//Get a DateFormat appropriate for the ULocale
DateFormat df = jc.getDateTimeFormat(DateFormat.FULL, DateFormat.FULL, jp);
//Output a formatted date
System.out.println(df.format(jc.getTime()));
//Output the era.
System.out.println(jc.get(Calendar.ERA));
//The era is a numeric value.  To get a meaningful value we need to
//get an instance of DateFormatSymbols and retrieve an array of era names.
//We can then use the era to retrieve the appropriate display name
DateFormatSymbols dfs = DateFormatSymbols.getInstance(jp);
//Concatenate the era and year.
String jYear = dfs.getEras()[jc.get(Calendar.ERA)]+jc.get(Calendar.YEAR);
System.out.println(jYear);

Output:

昭和46年10月22日金曜日 12時53分44秒アメリカ合衆国 (ニューヨーク)
234
昭和46

Discussion:

The Japanese year is represented by the year of the Emperors reign.  This makes it impossible to programmatically calculate the year since the length of an Emperor's reign fluctuates.  We will rely on the data stored in the CLDR and access it via icu4j.