Reputation: 2441
I know that struts2 can convert strings to Dates when populating the fields of my controller, however, it does so assuming the date string is in SHORT format. Is there a way to specify a different format for struts to use (for example, 'yyyy-MM-dd')?
Upvotes: 3
Views: 2581
Reputation: 23587
You need to create your own CustomType converter which can change the given date to any format. Something like
public class MyDateConvertor extends StrutsTypeConverter {
public Object convertFromString(Map context, String[] values, Class
toClass) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = (Date) sdf.parse(values[0]);
return new java.sql.Date(date.getTime()) ;
} catch (ParseException e) {
return values[0];
}
}
public String convertToString(Map context, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(o);
}
}
You can get more details form Struts2 official documents and here are the details
Struts2 Custom Type Conversion
Upvotes: 4