- Java Internationalization Cookbook
- Locales
- Dates and Times
- Calendars
- Gregorian Calendar
- Hebrew Calendar
- Japanese Calendar
- Chinese Calendar
- Find the Chinese zodiac for a Gregorian year
- Get the name of the current month
- Get the first day of the week
- Add time to Calendar
- Get an array of Holidays
- Find the date for the Chinese New Year
- Get all the Era names for the Japanese Calendar
- Get the Japanese era for a Gregorian date
- Formating dates and times
- Calendars
- Numerical Systems
- Misc
- Resource Bundles
- Unicode, Transliteration, and Charactersets
Java Cookbook
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.
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search
Custom Search