2012-09-25 46 views
1

我想將時間段格式化爲英語和其他語言,like Joda Time does圖書館到Java只打印最重要的字段的打印時間段

但是,我想要一個簡單的方法來列出最重要的一兩個字段,例如「2年和3個月」或「5天」,而無需編寫代碼來處理此問題。 Joda Time的問題是,除非您編寫代碼,否則它會給您輸出「2年,3個月和5天」。

有像Pretty Time這樣的圖書館正是我想要的,但只是與現在的時間進行比較,比如「3個月前」。我只想「3個月」。

當然,必須有一個圖書館,像美女時代的行爲,但一般的持續時間?

我特別使用Grails/Groovy,但普通的Java解決方案同樣可以接受。

+0

有時,當你有特定的要求,你必須寫一些代碼。你應該能夠複製幾乎所需的東西並擴展它。您甚至可以將修改作爲補丁提供,以便其他人可以利用您的改進。 –

+0

@PeterLawrey你是什麼意思的「具體」?你的意思是特定於我 - 即獨特?那你是完全正確的;然而我只是不能相信那種必然性是特定於我的! – Fletch

+0

在這種情況下,對開源項目提供任何改進將會非常有用,以便其他人可以使用它們。 –

回答

1

爲什麼你不能使用喬達時間寫一點代碼?我也有類似的問題,因爲你已經和我解決它絲毫的實用方法是這樣的:

DateTime dt = new DateTime(); // Now 
DateTime plusDuration = dt.plus(new Duration(110376000000L)); // Now plus three years and a half 

// Define and calculate the interval of time 
Interval interval = new Interval(dt.getMillis(), plusDuration.getMillis()); 

// Parse the interval to period using the proper PeriodType 
Period period = interval.toPeriod(PeriodType.yearMonthDayTime()); 

// Define the period formatter for pretty printing the period 
PeriodFormatter pf = new PeriodFormatterBuilder() 
     .appendYears().appendSuffix("y ", "y ") 
     .appendMonths().appendSuffix("m", "m ").appendDays() 
     .appendSuffix("d ", "d ").appendHours() 
     .appendSuffix("h ", "h ").appendMinutes() 
     .appendSuffix("m ", "m ").appendSeconds() 
     .appendSuffix("s ", "s ").toFormatter(); 

// Print the period using the previously created period formatter 
System.out.println(pf.print(period).trim()); 

也許這不是你在找什麼,但我希望它能幫助。

問候。

+0

謝謝,但我希望避免編寫代碼... – Fletch

+0

你沒有寫上面的任何代碼。看起來你不想添加任何代碼? –

+0

@PeterLawrey理想情況下不:-)。無論如何,上面的代碼實際上並不符合要求,所以我將不得不編寫它。例如,如果沒有月/年,只能追加幾天。 – Fletch