2
我正在从<p:calendar>
组件中选择一个日期,我希望将当前时间附加到所选日期。如何使用Primefaces中的当前TimeStamp获取选定日期?
现在假设时间是12/13/13 04:30:12
。
我从日历中选择日期为12/17/13
,我想将它保存为12/17/13 04:30:12
。
我正在从<p:calendar>
组件中选择一个日期,我希望将当前时间附加到所选日期。如何使用Primefaces中的当前TimeStamp获取选定日期?
现在假设时间是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);
}
}
更多信息:
的转换器是将日期为'太阳12月22日00:00:00 MST 2013',但我想它作为'MM/DD/yyyy'我曾经使用过''但它没有发生。 –
09Q71AO534