SpringBoot 以字符串格式传入时间
- controller
@PostMapping("/add")
public RestResult<String> publishComment(@RequestBody @Valid CommentRequest request) {
return commentService.publishComment(request);
}
- domain
@ApiModel("评论模型")
@Data
public class CommentRequest {
String userNo;
String nickName;
String avatar;
@NotNull
@ApiModelProperty(notes = "评论的业务类型 动态POST")
Subject subject;
@NotNull
@ApiModelProperty(notes = "评论的业务id 如动态id")
String subjectId;
@ApiModelProperty(notes = "回复类型 1评论动态 2回复评论 3回复的回复(带@某人)")
int type;
@NotNull
@ApiModelProperty(notes = "回复目标id,如果是回复评论,则此是被回复评论的id")
String replayId;
@ApiModelProperty(notes = "评论内容")
String comment;
@ApiModelProperty(notes = "评论图片链接")
String image;
@ApiModelProperty(notes = "发表评论时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date publishDate;
}
- 测试请求
使用postman
{
"avatar": "http://cdn.xxx.com/files/WC~klqDCTaylCz8BweyiH@1551943054015.jpg",
"comment": "狗子",
"image": null,
"nickName": "晨猫",
"replayId": "1974",
"subject": "YOUFAN",
"subjectId": "1974",
"type": "1",
"publishDate":"2019-05-28 16:51:52",
"userNo": "U4883419696379901484AC0E985090C0"
}
- 出现问题
接收到的入参 publishDate 时间比传入的时间多了8个小时(2019-05-29 00:51:52)
- 问题分析
多8小时,我们所在的时区是在东八区,是不是应该设置一下时区呢?
- 解决方案
将publishDate入参的@JsonFormat设置时区为东八区
@ApiModelProperty(notes = "发表评论时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
Date publishDate;
测试通过。
- 注意
添加 jackson 依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>