【问题标题】:Convert time interval to text in different languages?将时间间隔转换为不同语言的文本?
【发布时间】:2013-02-04 18:34:10
【问题描述】:

有没有简单的方法将时间间隔(年龄)转换为文本? 例如 - 年龄是 25.45 岁。我需要转换为“25 年 3 个月 1 天”。问题不在于数字 25、3、1,而是如何使用正确的形式(复数、变格)将年/月/日翻译成不同的语言。英语似乎很容易硬编码,但其他语言则不然,我更喜欢一些通用的解决方案。

数字 / 英语 / 捷克语 / ...
1 / 天 / 窝
2 / 天 / dny
5 / 天 / dnů
...

【问题讨论】:

标签: java date


【解决方案1】:

Joda time 很容易做到这一点。

例如:

public static void main(String[] args) {
  PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder()
    .appendDays()
    .appendSuffix(" day", " days")
    .appendSeparator(" and ")
    .appendMinutes()
    .appendSuffix(" minute", " minutes")
    .appendSeparator(" and ")
    .appendSeconds()
    .appendSuffix(" second", " seconds")
    .toFormatter();

  Period period = new Period(72, 24, 12, 0);

  System.out.println(daysHoursMinutes.print(period));
  System.out.println(daysHoursMinutes.print(period.normalizedStandard()));
}

将打印:

24 minutes and 12 seconds
3 days and 24 minutes and 12 seconds

另请参阅:Period to string

【讨论】:

  • 感谢您的示例,但它显示了如何仅针对英语对其进行硬编码。更喜欢通用解决方案。不能使用方法“appendSuffix(StringsingularText,String multipleText)”,因为不考虑复数形式的变格...
【解决方案2】:

JodaTime 的大多数格式化程序都可以做到这一点。 Look at the javadoc of PeriodFormat as an example.

上面写着:

Controls the printing and parsing of a time period to and from a string.

This class is the main API for printing and parsing used by most applications. Instances of this class are created via one of three factory classes:

PeriodFormat - formats by pattern and style
ISOPeriodFormat - ISO8601 formats
PeriodFormatterBuilder - complex formats created via method calls
An instance of this class holds a reference internally to one printer and one parser. It is possible that one of these may be null, in which case the formatter cannot print/parse. This can be checked via the isPrinter() and isParser() methods.

The underlying printer/parser can be altered to behave exactly as required by using a decorator modifier:

withLocale(Locale) - returns a new formatter that uses the specified locale
This returns a new formatter (instances of this class are immutable).
The main methods of the class are the printXxx and parseXxx methods. These are used as follows:

 // print using the default locale
 String periodStr = formatter.print(period);
 // print using the French locale
 String periodStr = formatter.withLocale(Locale.FRENCH).print(period);

 // parse using the French locale
 Period date = formatter.withLocale(Locale.FRENCH).parsePeriod(str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2021-05-20
    • 2019-12-03
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多