用注解实现后端时间格式化

编程入门 行业动态 更新时间:2024-10-07 20:26:36

用<a href=https://www.elefans.com/category/jswz/34/1768912.html style=注解实现后端时间格式化"/>

用注解实现后端时间格式化

问题:
在前端要求的特定格式下后端需要做格式的转化
如果在数据库中做类型转化时后端实体的Date数据类型无法接收到

数据库的格式化内容产生报错

解决:
在前端页面展示及其前端传入时间方面,后端人员通常需要进行处理,而使用spring框架的@JsonFormat和@DateTimeFormat注解就可以实现后台时间格式的处理.

@JsonFormat(timezone = "GMT+8",pattern = "yyyy年MM月dd日 HH:mm")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @ApiModelProperty(value = "创建时间")
private Date createTime;

@JsonFormat

这个注解表示后端返回前端的Json格式类型
timezone参数表示时区设置,这里写东八区北京时间
pattern参数表示后端格式化时间的格式

这是数据库的时间格式

{"type_dictText": "日报","createTime": "2020年03月06日 22:46","id": "2706cfed059df3a440dd728f9dc9bdaf",}

这是后端返回前端的Json格式类型,可见时间已经完成格式化

@DateTimeFormat

这个注解表示后端对于前端传入时间格式的校验
pattern参数表示校验的格式

{"success": false,"message": "操作失败,org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'prjWorkReport' on field 'createTime': rejected value [1111]; codes [typeMismatch.prjWorkReport.createTime,typeMismatch.createTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [prjWorkReport.createTime,createTime]; arguments []; default message [createTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.jeecgframework.poi.excel.annotation.Excel @com.fasterxml.jackson.annotation.JsonFormat @org.springframework.format.annotation.DateTimeFormat @io.swagger.annotations.ApiModelProperty java.util.Date] for value '1111'; nested exception is java.lang.IllegalArgumentException: Invalid format: \"1111\" is too short]","code": 500,"result": null,"timestamp": 1584329964105
}

当createTime前端传入参数@DateTimeFormat不为规定格式时的报错信息
当传入正确时间格式时的

{"type_dictText": "日报","createTime": "2020年03月06日 22:46","id": "2706cfed059df3a440dd728f9dc9bdaf",}

返回的Json数据

更多推荐

用注解实现后端时间格式化

本文发布于:2024-02-14 11:32:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1763433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   后端   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!