How to Convert String to Date using MapStruct in Java?
Asked Answered
L

2

11

I am using MapStruct to map values from a source to a target class. The source class has a String property and the target class has a java.util.Date property. The source property is like this: "yyyy-mm-dd". And I want to convert this String property to a Date property. How can I do that using MapStruct? Thank you!

Lois answered 24/3, 2020 at 17:20 Comment(0)
M
13

MapStruct takes care of String to Date conversions automatically. If you need to specify format of your date you can do it like this:

@Mapping(target = "date", dateFormat = "yyyy-MM-dd")
Destination map(Source source);

//For datetime
@Mapping(target = "date", dateFormat = "yyyy-MM-dd'T'HH:mm:ss")
Destination map(Source source);

Where target = "date" is the name of your property. You can find more about this in MapStruct documentation.

Mahayana answered 26/3, 2020 at 7:9 Comment(0)
H
2

From the official guide, if you have multiple dates, you can use this:

public class DateMapper {

    public String asString(Date date) {
        return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
            .format( date ) : null;
    }

    public Date asDate(String date) {
        try {
            return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
                .parse( date ) : null;
        }
        catch ( ParseException e ) {
            throw new RuntimeException( e );
        }
    }
}

And after in your mapper:

@Mapper(uses=DateMapper.class)
public interface CarMapper {

    CarDto carToCarDto(Car car);
}
Herne answered 13/7, 2022 at 14:51 Comment(1)
Nice solution.. this should be accepted answer..Sweeting

© 2022 - 2024 — McMap. All rights reserved.