• 【精品】Springboot 接收发送日期类型的数据


    问题

    在这里插入图片描述

    无法请求到后台,后台报错:[Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property

    在这里插入图片描述

    2023-10-02T09:26:16.069+08:00  WARN 14296 --- [p-nio-80-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.tiku.common.bean.ResultBean com.tiku.controller.manger.BookController.list(com.tiku.domain.query.BookQuery) with 2 errors: [Field error in object 'bookQuery' on field 'beginTime': rejected value [2000-12-12 12:12:12]; codes [typeMismatch.bookQuery.beginTime,typeMismatch.beginTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookQuery.beginTime,beginTime]; arguments []; default message [beginTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'beginTime'; Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value [2000-12-12 12:12:12]]] [Field error in object 'bookQuery' on field 'endTime': rejected value [2020-12-12 12:12:12]; codes [typeMismatch.bookQuery.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookQuery.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'endTime'; Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value [2020-12-12 12:12:12]]] ]
    
    • 1

    方式一

    在application.yml中添加:

    spring:
      mvc:
        format:
          date-time: yyyy-MM-dd HH:mm:ss
      #时间格式:返回格式化日期
      jackson:
        date-format: yyyy-MM-dd HH:mm:ss
        time-zone: GMT+8
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    方式二

    在类的属性上添加注解:

    // 接收时间类型
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    //返回时间类型
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime beginTime;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    说明:

    • @DateTimeFormat :该注解自动会解析处理,会把字符串类型 按照格式yyyy-MM-dd HH:mm:ss 转换成时间类型
    • @JsonFormat:该注解是从数据库查询出来,返回到页面的的转换. 把时间类型 转换成JSON格式类型,前提取出进行展示.

    小结

    实际项目开发中,一般采用第一种方式全局设置日期处理方式,采用第二种方式针对特定情况进行处理。

  • 相关阅读:
    Matlab学习笔记
    产品心理学:识知偏见,我们和自己开的玩笑
    0-30 VDC 稳压电源,电流控制 0.002-3 A
    npm如何发布自己的插件包
    对coredns解析外部域名的一点理解
    前端基础建设与架构20 如何理解前端中面向对象的思想?
    iOS开发:Mach-O入门理解
    向量数据库
    电子工艺卡在汽车制造流程中的应用
    JS逆向核心流程
  • 原文地址:https://blog.csdn.net/lianghecai52171314/article/details/133484413