• 项目中遇到的LocalDateTime时间格式转换问题


    最近在重构项目时,把java.util.Date类型改成了java.time.LocalDateTime,但是遇到一点小问题,在这里分享一下。

    后端代码:

    1. @Data
    2. public class RoleChengwei {
    3. @Id
    4. private String id;
    5. /**
    6. * 是否在使用
    7. */
    8. private Integer state;
    9. /**
    10. * 角色id
    11. */
    12. private String roleId;
    13. /**
    14. * 称谓id
    15. */
    16. private Integer chengweiId;
    17. /**
    18. * 装饰过期时间
    19. */
    20. @DateTimeFormat(pattern = "yyyy-MM-dd")
    21. @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    22. private LocalDateTime endTime;
    23. }

    前端代码:

    1. $("#end_time").datebox({
    2. width: 160,
    3. showSeconds: true,
    4. required: true
    5. });

    前端界面截图如下

    前端使用的是easyui框架,datebox就是日期框(只包含年月日的日期),在数据传到后端时,发生类型转换错误

    1. org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
    2. Field error in object 'roleChengwei' on field 'endTime': rejected value [2022-08-28]; codes [typeMismatch.roleChengwei.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [roleChengwei.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'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2022-08-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-08-28]]

    当看到这个报错信息的时候,其实就是时间格式不兼容,想着java.time包下应该有日期类型,果然,LocalDate就是java.time包下的,把以上实体类endTime属性的类型改成LocalDate,问题解决。

    1. @Data
    2. public class RoleChengwei {
    3. @Id
    4. private String id;
    5. /**
    6. * 是否在使用
    7. */
    8. private Integer state;
    9. /**
    10. * 角色id
    11. */
    12. private String roleId;
    13. /**
    14. * 称谓id
    15. */
    16. private Integer chengweiId;
    17. /**
    18. * 装饰过期时间
    19. */
    20. @DateTimeFormat(pattern = "yyyy-MM-dd")
    21. @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    22. private LocalDate endTime;
    23. }
  • 相关阅读:
    193页10万字一网统管解决方案2022
    作业比赛编号 : 1280 - 2022年春季学期《算法分析与设计》练习15
    Access所有记录中均未找到搜索关键字
    读书笔记--未来简史关键金句和阅读感悟
    Kotlin 中的数据类型有隐式转换吗?
    AIGC(生成式AI)试用 12 -- 年终再总结
    Python数据采集:抓取和解析XML数据
    注解与反射
    【day9.30】消息队列实现进程间通信
    JS实时获取录音数据并播放
  • 原文地址:https://blog.csdn.net/heyl163_/article/details/126570690