Java中的时间间隔本地化

时间:2014-07-02 06:45:22

标签: java time localization jodatime intervals

我需要将时间间隔表示为这样的本地化字符串:10 hours 25 minutes 1 second取决于Locale。 用英语手工实现很容易: String hourStr = hours == 1 ? "hour" : "hours"等。

但是我需要根据不同语言的规则使用一些“开箱即用”的Java(可能是Java8)机制。 Java是否拥有它,或者我需要为自己在app中使用的每个Locale实现它?

1 个答案:

答案 0 :(得分:3)

看看Joda-Time。它支持2.5版本的英语,丹麦语,荷兰语,法语,德语,日语,波兰语,葡萄牙语和西班牙语。

Period period = new Period(new LocalDate(2013, 4, 11), LocalDate.now());
PeriodFormatter formatter = PeriodFormat.wordBased(Locale.GERMANY);
System.out.println(formatter.print(period)); // output: 1 Jahr, 2 Monate und 3 Wochen

formatter = formatter.withLocale(Locale.ENGLISH);
System.out.println(formatter.print(period)); // output: 1 Jahr, 2 Monate und 3 Wochen (bug???)

formatter = PeriodFormat.wordBased(Locale.ENGLISH);
System.out.println(formatter.print(period)); // output: 1 year, 2 months and 3 weeks

然而,您可能会调整interpunctuation chars。为此,您可能需要复制和编辑类路径中具有此格式的messages-resource-files(此处为英文版本):

PeriodFormat.space=\ 
PeriodFormat.comma=,
PeriodFormat.commandand=,and 
PeriodFormat.commaspaceand=, and 
PeriodFormat.commaspace=, 
PeriodFormat.spaceandspace=\ and 
PeriodFormat.year=\ year
PeriodFormat.years=\ years
PeriodFormat.month=\ month
PeriodFormat.months=\ months
PeriodFormat.week=\ week
PeriodFormat.weeks=\ weeks
PeriodFormat.day=\ day
PeriodFormat.days=\ days
PeriodFormat.hour=\ hour
PeriodFormat.hours=\ hours
PeriodFormat.minute=\ minute
PeriodFormat.minutes=\ minutes
PeriodFormat.second=\ second
PeriodFormat.seconds=\ seconds
PeriodFormat.millisecond=\ millisecond
PeriodFormat.milliseconds=\ milliseconds

从版本2.5开始,也可以应用复杂的正则表达式来建模更复杂的复数规则。就我个人而言,我认为它对用户不友好,正则表达可能不足以满足阿拉伯语这样的语言(我的第一印象)。本地化还有其他限制,请参阅此pull request in debate

附注:Java 8绝对无法进行本地化的持续时间格式化。

2015-08-26更新:

使用我的库Time4J-v4.3(在Maven Central中可用)的版本,可以使用更强大的解决方案,它支持当前的45种语言:

import static net.time4j.CalendarUnit.*;
import static net.time4j.ClockUnit.*;

// the input for creating the duration (in Joda-Time called Period)
IsoUnit[] units = {YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS};
PlainTimestamp start = PlainDate.of(2013, 4, 11).atTime(13, 45, 21);
PlainTimestamp end = SystemClock.inLocalView().now();

// create the duration
Duration<?> duration = Duration.in(units).between(start, end);

// print the duration (here not abbreviated, but with full unit names)
String s = PrettyTime.of(Locale.US).print(duration, TextWidth.WIDE);

System.out.println(s);
// example output: 1 year, 5 months, 7 days, 3 hours, 25 minutes, and 49 seconds

为什么Time4J会更好地解决您的问题?

  • 它有一种更具表现力的方式来说明应该计算持续时间的单位。
  • 它支持45种语言。
  • 它支持有时复杂的多语言规则,包括从阿拉伯语到右到左的脚本,而不需要手动配置
  • 它支持依赖于区域设置的列表模式(使用逗号,空格或单词,如&#34;和&#34;)
  • 它支持3种不同的文字宽度:WIDE,ABBREVIATED(SHORT)和NARROW
  • 与Java-8的互操作性更好,因为Time4J可以理解java.time.Periodjava.time.Duration等Java-8类型。