Search code examples
javamappingorika

Mapping objects with Date and Timestamp with Orika


I use Orika for mapping objects.

I want to format the fields Date and Timestamp with the format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

For the fields Date, I resolve the problem with:

    @Override
public void configure(final MapperFactory orikaMapperFactory) {

    orikaMapperFactory.getConverterFactory().registerConverter(new DateToStringConverter("yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX"));

    orikaMapperFactory.classMap(OrderDTO.class, Order.class).byDefault().register();
}

But the fields TimeStamp I don't know how to do it.


Solution

  • I resolve the problem with:

    public class OrikaTimestampConverter extends CustomConverter<Timestamp, String> {
    
    private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    
    @Override
    public String convert(Timestamp source, Type<? extends String> destinationType, MappingContext mappingContext) {
    
        Date date = new Date(source.getTime());
    
        return formatter.format(date);
    } }
    

    And added:

    orikaMapperFactory.getConverterFactory().registerConverter(new OrikaTimestampConverter());