springboot接收日期类型参数

 

如果使用Get请求,直接使用对象接收,则可以使用@DateTimeFormat注解进行格式化,如:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startBuyDate;

如果使用Post请求,@RequestBody接收请求体参数,默认解析日期格式为yyyy-MM-dd HH:mm:ss , 如果需要接收其他格式的参数,则可以使用@JsonFormat注解,如:

@JsonFormat(timezone="GMT+8",pattern="yyyy-MM-dd")
private Date buyDate;

也可以使用java8新增的LocalDate自定义序列化,如:

@Configuration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            builder.locale(Locale.CHINA);
            builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
            builder.modules(new TimeModule());
        };
    }
}
public class TimeModule extends SimpleModule {

    public TimeModule() {
        super(PackageVersion.VERSION);
        this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
        this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
        this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
        this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
    }
}
//yyyy-MM-dd HH:mm:ss
private LocalDateTime buyDateTime;

//yyyy-MM-dd
private LocalDate buyDate;

//HH:mm:ss
private LocalTime buyTime;

 

posted @ 2020-10-12 11:12  HelloWorld102  阅读(8561)  评论(0编辑  收藏  举报