是否有简单的方法将时间间隔(年龄)转换为文本? 例如 - 年龄是25.45岁。我需要转换为“25年3个月,1天”。问题不是关于数字25,3,1,而是如何使用将正确的形式(复数,变体)翻译成不同语言的年/月/日。英语似乎很容易硬编码,但其他人不是,我宁愿一些通用的解决方案。将时间间隔转换为不同语言的文本?
数字/英文/捷克/ ...
1 /天/书房
2 /天/ DNY
5 /天/ DNU
...
是否有简单的方法将时间间隔(年龄)转换为文本? 例如 - 年龄是25.45岁。我需要转换为“25年3个月,1天”。问题不是关于数字25,3,1,而是如何使用将正确的形式(复数,变体)翻译成不同语言的年/月/日。英语似乎很容易硬编码,但其他人不是,我宁愿一些通用的解决方案。将时间间隔转换为不同语言的文本?
数字/英文/捷克/ ...
1 /天/书房
2 /天/ DNY
5 /天/ DNU
...
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);
乔达时间会做到这一点很容易地。
例如:
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
谢谢你的例子,但它显示了如何硬编码仅适用于英语语言。更喜欢通用解决方案。不能使用方法“appendSuffix(String singularText,String pluralText)”,因为不考虑复数形式的变体... –
http://stackoverflow.com/questions/1440557/joda-time-的可能的复制句号到字符串 –
不是真正的复制品,因为海报并不特别需要JODA时间解决方案。 –
可能相关:http://stackoverflow.com/questions/7455513/is-there-a-java-translation-library-that-works-offline – hyde