How do I correctly repopulate a <sj:datepicker timepicker=“true”>?

寵の児 提交于 2019-12-11 09:23:56

问题


I'm using the Struts2-jQuery Datepicker with the Timepicker Addon.

Assuming that a java.util.Date object is returned form an Action getMyDate() getter method:

<sj:datepicker displayFormat="dd/mm/yy" 
            timepickerFormat="HH:mm"
                  timepicker="true" 
                        name="myDate" />

This always results in the date being populated correctly, but the timepicker is always 00:00.


回答1:


Ok, I've found the time to expand the solution I've figured out on 18 december and briefly mentioned in the comments.

The Problem

The <sj:datepicker timepicker="true"> tag correctly parses a Date object, but not its String representation. This is reported in Issue 1057, with status accepted but still not fixed.

This works:

<sj:datepicker displayFormat="dd/mm/yy" 
                  timepicker="true" 
                       value="%{new java.util.Date()}" />

This does NOT work:

<sj:datepicker displayFormat="dd/mm/yy" 
                  timepicker="true" 
                       value="%{'07/01/2015 14:42'}" />

When not using a Converter, you need to send the format of the date-time to a String variable, instead than to a Date one:

<sj:datepicker displayFormat="dd/mm/yy" 
                  timepicker="true" 
                        name="dateStr" />
private String dateStr; 
public void setDateStr(String dateStr){
    this.dateStr = dateStr;
}
public String getDateStr(){
    return dateStr;
}

If you need a Date (you probably do), you can use a String Getter and Setter, that will handle the parsing and the formatting between Date and String:

private static final String FORMAT = "dd/MM/yyyy HH:mm";

private Date date; 
public void setDateStr(String dateStr){
    date = new SimpleDateFormat(FORMAT,Locale.ITALIAN).parse(dateStr);
}
public String getDateStr(){
    return new SimpleDateFormat(FORMAT,Locale.ITALIAN).format(date);
}

But both this methods, due to the bug linked above, won't work. The solution is so easy that made me laugh in my last comment to the question:

The Solution

Use a String setter, and a Date getter, then it will work perfectly:

<sj:datepicker displayFormat="dd/mm/yy" 
                  timepicker="true" 
                        name="dateStr" 
                       value="date" />
private Date date; 
public void setDateStr(String dateStr){
    date = new SimpleDateFormat(FORMAT,Locale.ITALIAN).parse(dateStr);
}
public Date getDate(){
    return date;
}

(or write a Converter).

Side note: timepickerFormat="HH:mm" is not needed because HH:mm (24 hours format) is already the default format. You need to change it only if you want the 12 hours display format.



来源:https://stackoverflow.com/questions/27544533/how-do-i-correctly-repopulate-a-sjdatepicker-timepicker-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!