gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:35:26 24 4
gpt4 key购买 nike

我正在从 <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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com