Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert String to Date using MapStruct in Java?

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!

like image 963
elvis Avatar asked Feb 23 '26 15:02

elvis


1 Answers

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.

like image 51
Tuom Avatar answered Feb 26 '26 04:02

Tuom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!