I am having this DTO:
public class TransactionRequestDTO {
private ZonedDateTime authDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@JsonProperty("authDate")
public void setAuthDate(String authDate) {
this.authDate = ZonedDateTime.parse(authDate);
}
}
I am making REST API call with this json:
{
"instrumentDate": "2020-02-28T05:50:24.000+02:00"
}
But I am receiving the Date as "2020-02-28T05:50:24.000+0200"
in setAuthDate()
(without ':').
Hence it is giving exception:
'java.time.format.DateTimeParseException' at ZonedDateTime.parse(authDate).
The Date & time represented in the string 2020-02-28T05:50:24.000+02:00
is of ISO-8601
format, so you can simply use OffsetDateTime
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@JsonProperty("authDate")
public void setAuthDate(String authDate) {
this.authDate = OffsetDateTime.parse(authDate);
}
In case if you want to still format into ZonedDateTime , just use the DateTimeFormatter with correct pattern
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
@JsonProperty("authDate")
public void setAuthDate(String authDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
this.authDate = ZonedDateTime.parse(authDate,formatter);
}
Your pattern is not correct. Change it to one of the following patterns:
yyyy-MM-dd'T'HH:mm:ss.SSSXXX
or
yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ
Demo:
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
String strDateTime = "2020-02-28T05:50:24.000+02:00";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
System.out.println(odt);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2020-02-28T05:50:24+02:00
2020-02-28T05:50:24+02:00
Also, since your date-time is with a timezone offset of +02:00
hours, you should consider using OffsetDateTime
instead of ZonedDateTime
. Some databases eg PostgreSQL do not support ZonedDateTime
, Instant
and OffsetTime / TIME [ WITHOUT TIMEZONE ]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.