如何在Primefaces中使用当前TimeStamp获取选定日期?

时间:2013-12-13 11:50:49

标签: jsf date jsf-2 primefaces timestamp

我从<p:calendar>组件中选择了一个日期,我希望将当前时间附加到所选日期。

enter image description here

假设现在时间为12/13/13 04:30:12

我从日历中选择了日期为12/17/13,我想将其保存为12/17/13 04:30:12

1 个答案:

答案 0 :(得分:3)

您可以实施自定义@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);
    }
}

更多信息: