javaapache-commons-beanutils

BeanUtils: populate String Date formatted map field to Date property


I've this Map<String, Object>:

Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "02/11/2018@11:29:03.463+0000");

My bean is:

public class MyBean {
  private Date date;
  // setters & getters
}

I'm trying to populate my map to bean:

MyBean bean = new MyBean();
BeanUtilsBean.getInstance().populate(bean, map);

I'm getting this error message:

ConversionException: DateConverter does not support default String to 'Date' conversion.

IMPORTANT: I can't change string format.

How could I solve it?


Solution

  • You can create an instance of DateTimeConverter and pass in your custom patterns. Here is an example:

    DateTimeConverter dateConverter = new DateConverter(null);
    dateConverter.setPatterns(new String[] {"dd/MM/yyyy@HH:mm:ss.SSSZ"});
    ConvertUtils.register(dateConverter, Date.class);