@JsonFormat 在处理 LocalDateTime 时,无法直接解析带有 UTC 时区标识的日期时间字符串(如 2025-03-21 10:03:36 UTC),因为 LocalDateTime 本身不包含时区信息。
分析:
LocalDateTime是一个不带时区的日期时间类。- 输入字符串
2025-03-21 10:03:36 UTC包含了时区信息(UTC),这与LocalDateTime的语义不匹配。 - 如果需要处理时区,应该使用
ZonedDateTime或OffsetDateTime。
方案一:将LocalDateTime改为ZonedDateTime
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.ZonedDateTime;
public class Example
{
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss 'UTC'", timezone = "UTC")
private ZonedDateTime timestamp;
// Getters and Setters
public ZonedDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(ZonedDateTime timestamp) {
this.timestamp = timestamp;
}或者
@JsonProperty(value = "created_at")
@JsonFormat( shape = JsonFormat.Shape.STRING,
pattern = "yyyy-MM-dd HH:mm:ss z",
timezone = "UTC")
private ZonedDateTime createdAt;方案二:自定义反序列化器
如果你必须使用 LocalDateTime,可以编写一个自定义反序列化器,在反序列化时移除 UTC 并解析为 LocalDateTime。
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String date = p.getText();
try {
// 移除 "UTC" 并解析
return LocalDateTime.parse(date.replace(" UTC", ""), formatter);
} catch (Exception e) {
throw new RuntimeException(e);
}
}import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.time.LocalDateTime;
public class Example {
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime timestamp;
// Getters and Setters
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
















