2013-12-13 93 views

回答

2

您可以实现自定义@FacesConverter并将其应用于<p:calendar>组件。

@FacesConverter("timestampConverter") 
public class TimestampConverter implements Converter { 

    @Override 
    public Object getAsObject(FacesContext facesContext, 
           UIComponent uIComponent, 
           String string) { 
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy"); 
     Date date = null; 
     Calendar calendar = Calendar.getInstance(); 
     try { 
      date = sdf.parse(string); 
      calendar.setTime(date); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     Calendar now = Calendar.getInstance(); 
     calendar.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY)); 
     calendar.set(Calendar.MINUTE, now.get(Calendar.MINUTE)); 
     calendar.set(Calendar.SECOND, now.get(Calendar.SECOND)); 
     Timestamp result = new Timestamp(calendar.getTime().getTime()); 
     return result; 
    } 

    @Override 
    public String getAsString(FacesContext facesContext, 
           UIComponent uIComponent, 
           Object object) { 
     if (object == null) { 
      return null; 
     }  
     return object.toString(); 
    } 
} 

getAsObject(..)方法你可以从前端收到年代String追加当前时间和构建Timestamp对象作为结果。

从facelet里(加我的测试按钮)的片段看起来是这样的:

<h:form> 
    <p:calendar value="#{myBean.date}" > 
     <f:converter converterId="timestampConverter" /> 
    </p:calendar> 
    <p:commandButton title="Test" action="#{myBean.testAction}" /> 
<h:form> 

,并在myBean类应该有一个date属性与相应的存取方法。

@RequestScoped 
@ManagedBean(name = "myBean") 
public class MyBean { 
    private Date date; 

    public Date getDate() { 
     return date; 
    } 

    public void setDate(Date date) { 
     return date; 
    } 

    public String testAction() { 
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YY HH:mm:ss"); 
     String output = sdf.format(date); 
     System.out.println("Selected date with timestamp: " + output); 
    } 
} 

更多信息:

+0

的转换器是将日期为'太阳12月22日00:00:00 MST 2013',但我想它作为'MM/DD/yyyy'我曾经使用过''但它没有发生。 – 09Q71AO534

相关问题