一、输出结果(Java8日期类型转换成字符串)二、接收参数(字符串转换Java8日期类型)
一、输出结果(Java8日期类型转换成字符串)方式1:可在对象属性上单独添加@com.fasterxml.jackson.annotation.JsonFormat
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime;
方式2:全局设置
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Configuration public class LocalDateTimeSerializerConfig { @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String dateTimePattern; @Bean public LocalDateTimeSerializer localDateTimeSerializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimePattern)); } @Bean public LocalDateTimeDeserializer localDateTimeDeserializer() { return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateTimePattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.serializerByType(LocalDateTime.class, localDateTimeSerializer()); builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer()); builder.simpleDateFormat(dateTimePattern); }; } }二、接收参数(字符串转换Java8日期类型)
方式1:可在controller方法参数上、对象属性上单独添加@org.springframework.format.annotation.DateTimeFormat
//controller方法参数上 @PostMapping("/date") public void date(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date) { // ... } //对象属性上 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime;
方式2:全局设置
通过application.yaml配置文件进行设置
spring: # springboot接受日期字符串成格式 mvc.format: date: yyyy-MM-dd date-time: yyyy-MM-dd HH:mm:ss time: HH:mm:ss
亦可添加jackson日期格式配置(非必须)
spring: # springboot接受日期字符串成格式 mvc.format: date: yyyy-MM-dd date-time: yyyy-MM-dd HH:mm:ss time: HH:mm:ss # jackson配置(jackson配置非必须,以下配置仅对输出结果为java.util.Date类型生效) jackson: # springboot输出日期格式配置 date-format: yyyy-MM-dd HH:mm:ss
参考:
https://www.baeldung.com/spring-date-parameters
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)