前后端时间使用LocalDateTime来传时间

warn:

* LocalDateTime 默认的时间格式是: yyyy-MM-ddTHH:mm:ss,中间多了一个 T 字,
* 但是对于往常的数据来说是没有 T 字的,这就会造成后端在接受或返回时间数据的时候出现异常,
* 解决方案下边会写。

首先看一下执行效果

 System.out.println( LocalDateTime.now());




2023-04-16T15:43:11.704

下边的两点本质都是基于修改这个传输的T

1.后端向前端传输时间

String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
输出:2023-04-16 15:45:27

现在已经把T去掉了 ,这样就可以把这个转化的string属性设置到对象中传输给前端。

2.前端向后端传输时间

这时候因为上边说的T的问题,前端传过来的肯定是带T的格式,现在后端需要设置一个配置类就可以解决。

package com.dtm.mallproject.config;

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;

/**
 * LocalDateTime 默认的时间格式是: yyyy-MM-ddTHH:mm:ss,中间多了一个 T 字,
 * 但是对于往常的数据来说是没有 T 字的,这就会造成后端在接受或返回时间数据的时候出现异常,
 * 解决方案如下(添加一个配置类,千万不要忘了 @Configuration 注解):
 * @author : 111
 * @program : Mall-Project
 * @description : 时间配置类
 */
@Configuration
public class LocalDateTimeSerializerConfig {
    @org.springframework.beans.factory.annotation.Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }
接收时间数据反序列化
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戏子☜已入画@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值