Dozer convert for String to date mapping but with optional date pattern? (i.e. yyyy-MM-dd[ HH:mm:ss] )

584 Views Asked by At

I have a Java spring app using Dozer allows for specifying the Date format in the custom .xml configuration file for mapping your fields as such:

<field>
  <a date-format="MM/dd/yyyy HH:mm:ss">dateString</a>
  <b>dateObject</b>
</field>

However, I am using Dozer to read .csv files and parse out the comma delimited data and I would like to also be able to read "MM/dd/yyyy" date as-well as full datetimes. Is it possible to add "optional" type patterns like can be used with DateTimeFormatter.of("MM/dd/yyyy[ HH:mm:ss]") using bracket (i.e. [ ]) notation?

I tried literally placing this pattern in the date-format attribute above but it reads the brackets (i.e. [ ]) as literals.

http://dozer.sourceforge.net/documentation/stringtodatemapping.html

1

There are 1 best solutions below

2
John Camerin On

The latest version of DozerMapper uses java.time.format.DateTimeFormatter to parse the string representation. Specifically, the value of date-format in your mapping spec is passed to DateTimeFormatter.ofPattern(String) The documentation for DateTimeFormatter indicates that the [] notation for optional fields is understood by DateTimeFormatter, implying that this should work for Dozer as well. My suggestion is to write a quick unitTest using DateTimeFormatter.ofPattern to test the pattern you are trying to use against various test values to make sure the pattern is working as you would expect and then plug that into Dozer.