2013-02-04 65 views
4

是否有簡單的方法將時間間隔(年齡)轉換爲文本? 例如 - 年齡是25.45歲。我需要轉換爲「25年3個月,1天」。問題不是關於數字25,3,1,而是如何使用將正確的形式(複數,變體)翻譯成不同語言的年/月/日。英語似乎很容易硬編碼,但其他人不是,我寧願一些通用的解決方案。將時間間隔轉換爲不同語言的文本?

數字/英文/捷克/ ...
1 /天/書房
2 /天/ DNY
5 /天/ DNU
...

+0

http://stackoverflow.com/questions/1440557/joda-time-的可能的複製句號到字符串 –

+0

不是真正的複製品,因爲海報並不特別需要JODA時間解決方案。 –

+0

可能相關:http://stackoverflow.com/questions/7455513/is-there-a-java-translation-library-that-works-offline – hyde

回答

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

喬達時間會做到這一點很容易地。

例如:

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

+2

謝謝你的例子,但它顯示瞭如何硬編碼僅適用於英語語言。更喜歡通用解決方案。不能使用方法「appendSuffix(String singularText,String pluralText)」,因爲不考慮複數形式的變體... –

相關問題