Issue
I have a DTO class that has an attribute of type OffsetDateTime and another class with the attribute LocalDateTime but at test time it returns the error below:
java.time.format.DateTimeParseException: Text '2022-07-19T16:21:33.3145924' could not be parsed at index 2
I'm mapping like this:
@Mapper
public interface PareInputMapper {
PareInputMapper INSTANCE = Mappers.getMapper(PareInputMapper.class);
@Mapping(target = "data", source = "data")
DataPareDto toResponse(DataPare domain);
List<PareDto> toResponseList(List<Pare> domainList);
default OffsetDateTime map(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(value, formatter);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("America/Sao_Paulo"));
return zonedDateTime.toOffsetDateTime();
}
}
In the DTO class the object is of type OffsetDateTime and in the domain class it is of type LocalDateTime.
Just remembering that these date attributes are inside a list that is in the DataPare and DataDto class.
Thanks in advance.
Solution
The error message you are getting should be clear. Your problem is a simple Java problem. The is that the String you insert in your value can´t be parsed since it looks different than the pattern the DateFormatter got. The String you provided looks like the default IsoLocalDateTime Pattern. You can simply replace
default OffsetDateTime map(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(value, formatter);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("America/Sao_Paulo"));
return zonedDateTime.toOffsetDateTime();
}
with
default OffsetDateTime map(String value) {
LocalDateTime localDateTime = LocalDateTime.parse(value);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("America/Sao_Paulo"));
zonedDateTime.toOffsetDateTime();
}
or with
default OffsetDateTime map(String value) {
LocalDateTime localDateTime = LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("America/Sao_Paulo"));
zonedDateTime.toOffsetDateTime();
}
You mentioned that this only occurs in your test Scenario. I would then assume that your value
string looks different in your test case.
Answered By - GJohannes
Answer Checked By - Terry (JavaFixing Volunteer)