将时间间隔转换为不同语言的文本?

时间:2013-02-04 18:34:11

标签: java date

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

number / English / Czech / ...
1 /天/ den
2 /天/ dny
5 /天/ dn ......
...

2 个答案:

答案 0 :(得分:4)

Joda时间很容易做到这一点。

例如:

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

答案 1 :(得分:3)

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);