SpringBoot--日期格式化
1、为了统一转转,可以使用日期格式化类
package com.example.demo.resource; 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 LocalDateConfig { @Value("${spring.jackson.data-format:yyyy-MM-dd HH:mm:ss}") private String pattern; @Bean public LocalDateTimeSerializer localDateTimeSerializer(){ return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){ return builder->builder.serializerByType(LocalDateTime.class,localDateTimeSerializer()); } }
2、定义Bean对象
如果使用通用的格式化,直接定义就OK,如果是需要个性化定制,在属性上单加注解即可。
package com.example.demo.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.time.LocalDateTime; @Data public class Order { @JsonFormat(pattern = "yyyy-MM-dd") private LocalDateTime payTime; private LocalDateTime newTime; }
3、Controller
新增Controller中方法对第2步中的两个属性赋值
@ResponseBody @RequestMapping(value = "/order") public Order getOrder(){ Order order = new Order(); order.setPayTime(LocalDateTime.now()); order.setNewTime(LocalDateTime.now()); return order; }
4、测试
------------------------------------------------------------------
-----------------------------------------------------------
---------------------------------------------
朦胧的夜 留笔~~
-----------------------------------------------------------
---------------------------------------------
朦胧的夜 留笔~~