SpringBoot 以字符串格式传入时间

博客主要讲述SpringBoot以字符串格式传入时间时遇到的问题。使用Postman测试请求,发现接收到的入参publishDate时间比传入的多8个小时。经分析,因处于东八区,需设置时区。解决方案是将publishDate入参的@JsonFormat设置时区为东八区,测试通过,同时要添加jackson依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot 以字符串格式传入时间

  1. controller
    @PostMapping("/add")
    public RestResult<String> publishComment(@RequestBody @Valid CommentRequest request) {
        return commentService.publishComment(request);
    }
  1. 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;
}
  1. 测试请求

使用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"
}
  1. 出现问题

接收到的入参 publishDate 时间比传入的时间多了8个小时(2019-05-29 00:51:52)

  1. 问题分析

多8小时,我们所在的时区是在东八区,是不是应该设置一下时区呢?

  1. 解决方案

将publishDate入参的@JsonFormat设置时区为东八区

    @ApiModelProperty(notes = "发表评论时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    Date publishDate;

测试通过。

  1. 注意
    添加 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>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值