JSF2.0 日期轉換
Jsf RI 包提供默認的日期轉換器 <f:
convertDateTime /> 但在使用時發(fā)現(xiàn)從數(shù)據(jù)讀出數(shù)據(jù)顯示的時候會少一天,比如:數(shù)據(jù)庫中的日期是2010-4-24 在經(jīng)過轉換器前還是這個日期,但轉換后顯示到界面上時就會顯示2010-4-23 ,無論設置格式還是時區(qū)都無效。
既然不好用就自定義一個轉換器,好在JSF2.0 自定義轉換器也非常的方便了
整個代碼如下:
import java.text.ParseException;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import cn.xiangyunsoft.utils.DateUtils;
import cn.xiangyunsoft.utils.StringUtils;
@FacesConverter(value = "dateConverter")
public class ConvertDate implements Converter {
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
if (StringUtils.isNotEmpty(arg2)) {
try {
return DateUtils.parseDate(arg2);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
if (arg2!=null){
return DateUtils.format((Date) arg2, "yyyy-MM-dd");
}
return null;
}
}
其中DateUtils 類就是常用的日期和字符串的轉換方法。
在XHTML 使用時如下:
<h:inputText id="#{cc.attrs.id}" value="#{cc.attrs.value}"
onkeydown="ctlent(event);" styleClass="#{cc.attrs.styleClass}">
<!--<f:convertDateTime pattern="yyyy-MM-dd" locale="zh-CN"/>-->
<f:converter converterId="dateConverter" />
</h:inputText>
posted on 2010-04-24 15:05
Libo 閱讀(1357)
評論(1) 編輯 收藏 所屬分類:
JSF 2