如何在Java-8中显示普通纪元("CE")?

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

以下代码不打印 "CE" 或 "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

当然,IsoEra.CE.name() 有帮助,但如果需要像 "common era" 或 "current era" 这样的完整显示名称,则无济于事。我认为这有点奇怪,因为 IsoEra 的 javadoc 在其 class 描述中明确提到了术语 "Current era"。它甚至不适用于根语言环境。这里的用例是为非宗教背景的客户提供服务。

这也无济于事:

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

我找到的唯一方法是:

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

有没有更好或更短的方法?

不,没有更好的方法!

说明:"Current era"(相应地"before current era")是ISO标准的"name of a field"(abstract/meta)。当然,这些字段也有 no(标准化)国家/地区特定翻译,并且没有打印此输出的模式。(根据标准,它们仅以英文引用,并且 jdk 分别只有 CE, BCE)。那么原始输出显示的是什么:

  AD
  Anno Domini

是正确的,并且是时代("in the current era" 的日期)的符合 ISO 标准的(英语)翻译。

为了解决这个问题,我完全同意你的方法(自定义日期格式),并深入细节:我不敢更改它的一行!

我看到的唯一节省潜力是 "initialization"(可能对 TextStyles 使用 EnumMap...以及...您想要支持多少种语言?)..和 "by refactoring".

感谢您的有趣 "problem",并提供解决方案!