【发布时间】:2013-12-13 11:50:49
【问题描述】:
我正在从 <p:calendar> 组件中选择一个日期,并且我希望将当前时间附加到所选日期。
假设现在时间是 12/13/13 04:30:12 。
我从日历中选择了日期为12/17/13,我想将其保存为12/17/13 04:30:12。
【问题讨论】:
标签: jsf date jsf-2 primefaces timestamp
我正在从 <p:calendar> 组件中选择一个日期,并且我希望将当前时间附加到所选日期。
假设现在时间是 12/13/13 04:30:12 。
我从日历中选择了日期为12/17/13,我想将其保存为12/17/13 04:30:12。
【问题讨论】:
标签: jsf date jsf-2 primefaces timestamp
您可以实现您的自定义@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 中的 sn-p(加上我的测试按钮)如下所示:
<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);
}
}
更多信息:
【讨论】:
Sun Dec 22 00:00:00 MST 2013,但我希望它为MM/dd/yyyy,我曾使用过<f:converDateTime pattern="MM/dd/yyyy"/>,但它没有发生。