localdate 年月转换_SpringBoot LocalDateTime日期转换

一、LocalDateTime日期转换两个问题

1.前端传入参数时String转换为Date。

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot

deserialize value of type `java.time.LocalDateTime` from String "2020-02-11 12:48:13": Failed to

deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-02-11

12:48:13' could not be parsed at index 10; nested exception is

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type

`java.time.LocalDateTime` from String "2020-02-11 12:48:13": Failed to deserialize

java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-02-11 12:48:13' could

not be parsed at index 10

at [Source: (PushbackInputStream); line: 4, column: 19] (through reference chain:

com.example.demo.model.Test["localDateTime"])

2.后台返回值时Date转换为String

LocalDateTime中间有个“T”,其他时间类型时间格式可读性也很差。

二、解决方案

编写一个时间配置类,使用HTTP消息转换器来格式化。

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

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 DateConfig {

@Bean

public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {

JavaTimeModule module = new JavaTimeModule();

module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

return builder -> {

builder.simpleDateFormat("yyyy-MM-dd hh:mm:ss");

builder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));

builder.modules(module);

};

}

}

三、验证效果

1.第一个问题解决效果图:

2.第二个问题解决效果图:

我们可以看到使用了HTTP消息转换器来格式化后,连Date类型也格式化正常了。

更多阅读

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值