jsf - 如何在 Primefaces 中获取带有当前时间戳的选定日期?

标签 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 .

最佳答案

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

更多信息:

关于jsf - 如何在 Primefaces 中获取带有当前时间戳的选定日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20565829/

相关文章:

date - 如何解决 h :inputText with Date value? 中的 "Conversion Error setting value ' 2013-10-2 6' for ' null Converter'"

css - JSF 数据表单元格在呈现条件下隐藏

jsf - 如何通过ajax验证两个密码字段?

java - jsf 中的文件保存对话框

ajax - 如何知道 JSF bean setter 是从 AJAX 事件调用还是作为表单 POST 处理的一部分调用

jsf - 将参数从资源包传递到除 **h :outputFormat** 之外的组件的消息

html - jsf 页面的中心组件

excel - 将十位数字转换为日期excel

java - 不考虑 java 周末和银行假日的耗时

function - 将谷歌表中的日期区域设置从公历转换为 Jalali 日历