Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display common era ("CE") in Java-8?

Following code does not print "CE" or "Current Era":

System.out.println(IsoEra.CE.getDisplayName(TextStyle.SHORT, Locale.UK)); // output: AD
System.out.println(IsoEra.CE.getDisplayName(TextStyle.FULL, Locale.UK)); // output: Anno Domini

Of course, IsoEra.CE.name() helps but not if the full display name like "common era" or "current era" is required. I consider this a little bit strange because the javadoc of IsoEra explicitly mentions the term "Current era" in its class description. It does not even work for root locale. The use-case here is to serve clients with a non-religious background.

This does not help, too:

LocalDate date = LocalDate.now();
String year = date.format(DateTimeFormatter.ofPattern("G yyyy", Locale.UK)); // AD 2015
System.out.println(year);

The only way I found was:

TextStyle style = ...;
Map<Long,String> eras = new HashMap<>();
long bce = (long) IsoEra.BCE.getValue(); // 0L
long ce = (long) IsoEra.CE.getValue(); // 1L
if (style == TextStyle.FULL) {
  eras.put(bce, "Before current era");
  eras.put(ce, "Current era");
} else {
  eras.put(bce, "BCE");
  eras.put(ce, "CE");
}
DateTimeFormatter dtf = 
  new DateTimeFormatterBuilder()
  .appendText(ChronoField.ERA, eras)
  .appendPattern(" yyyy").toFormatter();
System.out.println(LocalDate.now().format(dtf)); // CE 2015

Is there any better or shorter way?

like image 664
Meno Hochschild Avatar asked Apr 07 '15 14:04

Meno Hochschild


1 Answers

No, there is no better way to do it!

Explanation: "Current era" (and accoridngly "before current era") is the "name of a field"(abstract/meta) of the ISO standard. Of course there is also no (standardized) country specific translation for these fields and no pattern which prints this output.(By the standard they are referenced in english only, and by jdk respectively only as CE, BCE). So what the original output shows:

  AD
  Anno Domini

is correct, and the ISO-conform (english) translation of the era (of a date which is "in the current era").

To solve this, I absolutely agree with your approach (of custom date formatting), and going deeper into details: I wouldn't dare to change a single line of it!

The only savings potential I see is in "initialization"(maybe use a EnumMap for the TextStyles...and ... how many languages do you want to support?) ..and "by refactoring".

Thank you for the interesting "problem", and providing a solution to it!

like image 96
xerx593 Avatar answered Oct 11 '22 17:10

xerx593