有没有简单的方法将时间间隔(年龄)转换为文本?例如 - 年龄是 25.45 岁。我需要转换为“ 25 年 3 个月 1 天”。问题不是关于数字 25,3,1,而是如何使用正确的形式(复数,变格)将年/月/日翻译成不同的语言。英语似乎很容易硬编码,但其他语言则不然,我更喜欢一些通用的解决方案。
number / English / Czech / ...
1 / day / den
2 / days / dny
5 / days / dnů
...
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
另请参阅:句点到字符串
JodaTime 可以用它的大多数格式化程序来做到这一点。 以 javadocPeriodFormat
为例。
它说:
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);