You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by "Bingel, Michael" <Mi...@paybox.net> on 2003/05/07 12:01:07 UTC
Problem with two-way converter for Date
Hi there,
we are creating a little internal web application with a lot of data fields.
Instead of using BeanUtils.copyProperties( ) with form and database beans
we just have a form container which already includes the database beans.
So when data is submitted, it directly ends up in the database beans.
Our problem are the date fields, for which I already created a converter
with the help of all the usefull postings in this mailing list. The dates
are stored correctly when they have the format "yyyy-MM-dd", but when the
JSP page reappears, the dat has suddenly changed the format to something
like "Thu Jan 02 00:00:00 CET 2003". And this won't save again.
Shouldn't the converter work both ways, from JSP to bean and vice versa ?
Or am I missing something here ? Help is really appreciated !
cheers Mike
--- snip --- some code ---
static DateConverter converter = new DateConverter();
static {
converter.setFormatPattern("yyyy-MM-dd");
ConvertUtils.register (converter, java.util.Date.class);
ConvertUtils.register (converter, String.class);
}
public class DateConverter implements Converter {
private String formatPattern = null;
public void setFormatPattern(String formatPattern) {
this.formatPattern = formatPattern;
}
protected Log log = LogFactory.getLog(DateConverter.class);
public Object convert(Class type, Object value) {
log.info("convert() - from " + value.getClass().getName() + " to " +
type.getName());
if (value == null) {
return null;
} else {
if ((value instanceof String) && (type == Date.class)) {
if (value == null || ((String)value).length() == 0) return
null;
try {
String s = value.toString();
SimpleDateFormat formatter = new
SimpleDateFormat(formatPattern);
return formatter.parse(s);
} catch (ParseException pe) {
log.warn("DateConverter: " + pe);
}
} else if ((value instanceof Date) && (type == String.class)) {
SimpleDateFormat formatter = new
SimpleDateFormat(formatPattern);
String dateString = formatter.format(value);
return dateString;
}
}
/*
throw new ConversionException("Could not convert "
+ value.getClass().getName() + " to "
+ type.getName() + "!");
*/
// hmmm, probably not the right action if converter does not convert
StringConverter stringConverter = new StringConverter();
return stringConverter.convert(type, value);
}
}