2013-04-23 59 views
1

我想創建一個Joda 2.2 DateTimeFormatter來重構我的代碼。我試圖重現行爲是編程Joda時間格式化程序

private String getSemesterLabel() { 
    StringBuilder sb = new StringBuilder(date.toString("yyyy")); 
    if (date.getMonthOfYear() < 7) { 
     sb.insert(0, "first semester "); 
    } else { 
     sb.insert(0, "second semester "); 
    } 
    return sb.toString(); 
} 

什麼是獲得DateTimeFormatter將封裝上述行爲的最簡單的方法?

+0

我看到你的評論和反對票因爲我已經閱讀了整個文檔,但找不到任何相關的東西。我發現的唯一方法是從頭開始創建一個完整的DateTimeFormatter,這太值得重構了。 因爲我不知道如何做某事(這說明我沒有看到任何細節,我可以提供)並不意味着這個問題是不合法的。 – clark 2013-04-23 15:05:31

+0

我想我完全誤解了你的問題。你希望找到一個理解學期概念的格式化程序嗎? – 2013-04-24 07:31:14

+0

我不知道你的意思是「單身」。我正在嘗試創建一個'DateTimeFormatter'對象來封裝上述代碼中描述的業務行爲。我不認爲答案就像'DateTimeFormat#forPattern(String)'一樣簡單。 如果您錯誤地投了票。我將不勝感激你投票回來。謝謝。 – clark 2013-04-24 08:06:11

回答

2

使用內置模式符號不能打印學期信息(請參閱此similar issue in a bug report)。你有兩個選擇:

  1. 從頭開始構建邏輯

    可以產生使用從DateTimeFormat類的靜態方法DateTimeFormatter實例:

    DateTimeFormatter format = DateTimeFormat.forPattern("yyyy"); 
    

    您也可以檢索月份從喬達DateTime通過呼籲:

    myDateTime.monthOfYear().get(); 
    


  2. 使用DateTimeFormatterBuilder構建一個格式化

    的替代,可能是使用DateTimeFormatterBuilder構建定製DateTimeFormatter顯示您的首選文本。喜歡的東西:

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); 
    builder.append(DateTimeFormat.forPattern("yyyy")); 
    builder.appendLiteral(' '); 
    builder.append(new SemesterPrinter()); 
    return builder.toFormatter(); 
    

    其中SemesterPrinter需要實現DateTimePrinter,並會承擔一切生產基礎上提供的日期信息的文本first semestersecond semester ..

+0

嗯,我看不出這將如何打印「第一學期」或「第二學期」...只打印年份是(非常)容易的部分... – 2013-04-24 07:17:40

+0

@LudovicPénet啊,第二個想到我可能誤解了題。我編輯了我的答案。 – 2013-04-24 07:28:25

+0

我擔心我確實必須從零開始構造DateTimePrinter ... – clark 2013-04-24 13:04:41