gpt4 book ai didi

java - Java 中的时间间隔本地化

转载 作者:搜寻专家 更新时间:2023-11-01 03:05:23 26 4
gpt4 key购买 nike

我需要将时间间隔表示为本地化字符串,如下所示:10 小时 25 分钟 1 秒,具体取决于 Locale。用英语手工实现很容易:字符串 hourStr = 小时数 == 1 ? “小时”:“小时”

但是根据不同语言的规则,我需要一些“开箱即用”的 Java(也许是 Java8)机制。Java有没有,还是需要我自己为应用中使用的每个Locale实现?

最佳答案

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

不过,您可以调整标点字符。为此,您可能需要复制和编辑类路径中具有这种格式(此处为英文变体)的消息资源文件:

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 种语言。
  • 它支持有时复杂的复数语言规则,包括从右到左的脚本,如阿拉伯语,无需手动配置
  • 它支持依赖于语言环境的列表模式(使用逗号、空格或“and”之类的词)
  • 它支持 3 种不同的文本宽度:WIDE、ABBREVIATED (SHORT) 和 NARROW
  • 与 Java-8 的互操作性更好,因为 Time4J 可以理解 Java-8 类型,如 java.time.Periodjava.time.Duration。<

关于java - Java 中的时间间隔本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com