SpringBoot项目——配置时间格式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/87886235

一、全局配置

application.properties中加入:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss 
spring.jackson.time-zone=GMT+8 
spring.jackson.serialization.write-dates-as-timestamps=false  

第一行设置格式:yyyy-MM-dd HH:mm:ss
第二行设置时区
第三行表示不返回时间戳,如果为true返回时间戳

二、实体类中的属性配置

在实体类中使用注解@JsonFormat

@JsonFormat(pattern = "yyyyMMdd HH:mm:ss",timezone = "GMT+8")
private Date createTime;

具体实例

1、实体类User.java
package com.gui.restful;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class User {
    private int id;

    @JsonFormat(pattern = "yyyyMMdd HH:mm:ss",timezone = "GMT+8")
    private Date createTime;

    public User(int id,Date createTime){
        this.id=id;
        this.createTime=createTime;
    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

2、控制类UserController.java
package com.gui.restful;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping
    public List<User> getAll(){
        List<User> list=new ArrayList<>();
        Calendar calendar=Calendar.getInstance();
        calendar.set(2020,Calendar.NOVEMBER,4,11,12,3);
        User user = new User(1,calendar.getTime());
        list.add(user);
        return list;
    }
}

3、配置文件application.properties:
server.port=8090
4、运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hju22/article/details/87886235