Joda 或 Java 日期和时间 API 中是否有任何本地化常量,如 "Today"、"Tomorrow"、"Yesterday" 等?

Are there any localized constants like "Today", "Tomorrow", "Yesterday" etc in Joda or Java Date and time API?

我必须实现使网站客户能够看到最近的交货日期的功能。几个例子:

Delivery available Today, June 20

Delivery available Tomorrow, June 21

Delivery available Tuesday, June 24

问题是这个 属性 被本地化为 6 种不同的语言,我想知道是否有办法不为时间副词(如“今天”和“明天”)创建本地化属性?也许有任何预定义的常量或枚举?

您可以使用getDisplayName method of Calendar;它 return 是您所需属性的本地化字符串。

这是获取所需属性字符串的方法。

Calendar cal = Calendar.getInstance();
String <attribute_localized> = cal.getDisplayName(Calendar.<attribute>, Calendar.LONG, Locale.<your_locale>);

但是请注意,该方法将 return null 用于任何数值;在这种情况下,您必须使用 get(Calendar.<attribute>)

方法

这是此代码的工作示例:

Calendar cal = Calendar.getInstance();

Locale myLocale = Locale.ENGLISH;
Integer year = cal.get(Calendar.YEAR);
Integer day_of_month = cal.get(Calendar.DAY_OF_MONTH);

String month = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, myLocale);
System.out.println("Today is " + day_of_month + " " + month + " " + year);
// Today is 20 June 2019

myLocale = Locale.ITALIAN;
month = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, myLocale);
System.out.println("Today is " + day_of_month + " " + month + " " + year);
// Today is 20 giugno 2019

仅供参考,标准 Java 和 Joda-Time 都没有这样的功能。

但是,我的库 Time4J 支持 90 多种语言的相对表达式,如 "today"、"tomorrow"、"yesterday" 或 "next Sunday"。使用测试时钟的示例:

  TimeSource<?> clock = () -> PlainTimestamp.of(2015, 8, 1, 10, 24, 5).atUTC();
  String durationInDays =
      PrettyTime.of(Locale.GERMAN).withReferenceClock(clock).printRelative(
          PlainTimestamp.of(2015, 8, 1, 17, 0).atUTC(),
          Timezone.of(EUROPE.BERLIN),
          TimeUnit.DAYS);
  System.out.println(durationInDays); // heute (german word for today)

您还可以通过调用以下方法获得这些表达式的单一翻译 PrettyTime.of(Locale.getDefault()).printToday() or printNext(Weekday) etc. If you are on Android you can use the sister Project Time4A. A list of supported languages is also documented。如果您错过了某种语言,请告诉我。