Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java LocalDateTime将无效日期解析为有效日期,并且不会引发任何异常_Java_Spring_Spring Boot - Fatal编程技术网

Java LocalDateTime将无效日期解析为有效日期,并且不会引发任何异常

Java LocalDateTime将无效日期解析为有效日期,并且不会引发任何异常,java,spring,spring-boot,Java,Spring,Spring Boot,我在Spring的API请求体中使用LocalDateTime @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-mm-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = Lo

我在Spring的API请求体中使用LocalDateTime

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-mm-dd HH:mm:ss")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  @JsonSerialize(using = LocalDateTimeSerializer.class)
  private LocalDateTime createdAt;
当我在请求中输入无效日期时,例如“2020-02-31 00:00:00”,它会自动转换为“2020-02-29 00:00:00”。如果日期无效,我想抛出异常。官方文件中提到将其转换为以前的有效日期

 In some cases, changing the specified field can cause the resulting date-time to become invalid,
 such as changing the month from 31st January to February would make the day-of-month invalid.
 In cases like this, the field is responsible for resolving the date.
 Typically it will choose the previous valid date, 
 which would be the last valid day of February in this example.

您需要为此编写一个自定义序列化程序

类CustomLocalDateTimeSerializer扩展了StdSerializer{
专用静态最终DateTimeFormatter格式化程序
=模式的日期时间格式(“yyyy-mm-dd HH:mm:ss”);
...
@凌驾
公共void序列化(LocalDateTime值、JsonGenerator生成器、SerializerProvider提供程序)
抛出IOException、JsonProcessingException{
//使用格式化程序进行验证。
//使用生成器和提供程序序列化该值。
}
}
然后您可以在注释中使用它

@JsonSerialize(使用=CustomLocalDateTimeSerializer.class)
请注意,格式化/解析无效值时引发异常


查看源代码以了解必须执行的操作。查看编写自定义序列化程序的示例。这类似于自定义反序列化程序。

请注意格式化模式字母的情况。我认为您的格式模式字符串中不是两次使用小写字母
mm
?请再查一下。