2011-04-13 64 views
5

有沒有一種方法來格式化日期對象顯示在選擇項目?格式日期內選擇項目

這裏是我的例子:

<h:selectOneMenu 
    label="Period" 
    value="#{myBean.periodStartEndList}" 
    id="periodStartEnd" 
    converter="genericConverter"> 

    <f:selectItem itemLabel="Choose one .." noSelectionOption="true" /> 

    <f:selectItems 
     value="#{myBean.periodStartEndList}" 
     var="periodStartEnd" 
     itemValue="#{periodStartEnd}" 
     itemLabel="#{periodStartEnd.map['dateStart']} -- #{periodStartEnd.map['dateEnd']}" /> 
</h:selectOneMenu> 

而且組合/選擇顯示這些:

Sun May 01 14:57:21 WIT 2011 -- Thu May 05 14:57:21 WIT 2011 
Fri May 06 14:57:21 WIT 2011 -- Tue May 10 14:57:21 WIT 2011 

我想有更簡單的東西,如:

01-05-2011 -- 05-05-2011 
06-05-2011 -- 10-05-2011 

我不知道如何做到這一點?

謝謝!

回答

3

您可以創建用於轉換的EL功能並使用它。檢查http://www.javabeat.net/tips/4-expression-language-in-jsp-20.htmlhttp://wiki.apache.org/myfaces/Parameters_In_EL_Functions。免責聲明:我從來沒有使用它,不知道它是否工作。

+0

+1的免責聲明。我認爲對於需要它的SO有很多答案。 – 2011-04-13 09:43:17

+1

另一個例子在這裏:http://stackoverflow.com/questions/2378826/facelets-and-jstl-converting-a-date-to-a-string-for-use-in-a-field/2381443#2381443 – BalusC 2011-04-13 11:31:05

+0

@阿迪:你好..感謝你的建議,看着它,我認爲它會工作得很好。但我很好奇使自己的EL函數在使用函數來設置日期的簡單應用程序管理bean上的優勢嗎? – bertie 2011-04-13 15:20:32

1

你需要使用日期格式化程序。假設返回Date對象,AFAIK #{periodStartEnd.map['dateStart']}最終將在toString()呼叫中結束。

我不確定JSF 2.0中的Java EL是否已經構建了函數參數,但是如果沒有,您可以使用JBoss EL(Java EL的擴展)。這樣,您可以提供一個格式化bean並使用類似#{formatter.format(periodStartEnd.map['dateStart'], 'dd-MM-yyyy')}

format然後將創建從格式字符串SimpleDateFormat並返回格式化的日期爲一個字符串。

您也可以傳入語言環境以提供本地化格式。

第三個替代方案是將格式化的字符串直接存儲在periodStartEnd中並訪問它們。

0

您可以使用f:convertDateTime並指定一種模式。

+0

那太棒了。你能舉個例子嗎?我在使用h:outputText時試過了,但我不知道如何爲上面的情況編寫它。 – bertie 2011-04-13 09:18:52

+0

難道你不能像在'outputText'中那樣把它放在'selectOneMenu'中嗎?如果您選擇的項目是日期,並且您將您的價值綁定到日期,那麼它應該有效。 – wjans 2011-04-13 09:30:50

+0

僅在項目值上運行,而不在項目標籤上運行。此外,他已經有了一個「genericConverter」值。 – BalusC 2011-04-13 11:32:10

0

你可以在你的bean使用轉換器的方法,如:

public class MyBean{ 
    ... 
     public String formatDate(Date fecha, String pattern) { 
      return (new SimpleDateFormat(pattern)).format(fecha); 
     } 
    ... 
} 

而且,在你的XHTML頁面內F:selectItems的:

<f:selectItems 
    value="#{myBean.periodStartEndList}" 
    var="periodStartEnd" 
    itemValue="#{periodStartEnd}" 
    itemLabel="#{myBean.formatDate(periodStartEnd.map['dateStart'],'dd-MM-yyyy')} -- #{myBean.formatDate(periodStartEnd.map['dateEnd'],'dd-MM-yyyy')}" />