By specifying the date-format at the field level, we can convert string to date and vice versa.
Example
<field>
<a>manufacturingDate</a>
<b date-format="MM/dd/yyyy HH:mm:ss:SS">dateString</b>
</field>
Find the below working application.
Product1.java
package com.sample.app.model;
import java.util.Date;
public class Product1 {
private Date manufacturingDate;
public Date getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(Date manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
@Override
public String toString() {
return "Product1 [manufacturingDate=" + manufacturingDate + "]";
}
}
Product2.java
package com.sample.app.model;
public class Product2 {
private String dateString;
public String getDateString() {
return dateString;
}
public void setDateString(String dateString) {
this.dateString = dateString;
}
@Override
public String toString() {
return "Product2 [dateString=" + dateString + "]";
}
}
date_to_string.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mapping>
<class-a>com.sample.app.model.Product1</class-a>
<class-b>com.sample.app.model.Product2</class-b>
<field>
<a>manufacturingDate</a>
<b date-format="MM/dd/yyyy HH:mm:ss:SS">dateString</b>
</field>
</mapping>
</mappings>
DateToString.java
package com.sample.app;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import org.dozer.DozerBeanMapper;
import com.sample.app.model.Product1;
import com.sample.app.model.Product2;
public class DateToString {
public static void main(String[] args) throws IOException {
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setMappingFiles(Arrays.asList("date_to_string.xml"));
Product1 product1 = new Product1();
product1.setManufacturingDate(new Date());
Product2 product2 = mapper.map(product1, Product2.class);
Product1 product1ConvertedBack = mapper.map(product2, Product1.class);
System.out.println(product1);
System.out.println(product2);
System.out.println(product1ConvertedBack);
}
}
Output
Product1 [manufacturingDate=Sun Feb 06 19:30:15 IST 2022] Product2 [dateString=02/06/2022 19:30:15:636] Product1 [manufacturingDate=Sun Feb 06 19:30:15 IST 2022]
Previous Next Home
No comments:
Post a Comment