为什么从数据库获取Timestamp类型数据类型和打印出来的不一样,如何进行转换

我想将"2021-01-26T22:52:00.000+0000"转换成正确的时间""2021-01-27 10:52:00"

image

这是从数据库获取的接口数据

{
    "code": "200",
    "status": "success",
    "message": "tenantMessage",
    "result": null,
    "detail": "添加tenantMessage",
    "data": {
        "technology": [
            {
                "id": 115,
                "title": "HTTPS原理(三次握手)",
                "userID": 500,
                "content": "客户端向服务器发送HTTPS请求,服务器将公钥以证书的形式发送到客户端(服务器端存放私钥和公钥)",
                "createDate": "2021-01-26T22:52:00.000+0000",
                "updateDate": "2021-01-26T22:52:00.000+0000",
                "tags": null,
                "qrCodePath": "upload/article/115/1611651120474/qr_161165112048364.png",
                "url": "http://www.xinlizhiyouni.com/myself/article/detail_phone.html?id=115"
            }
       ]
   }
}
package cn.spring.inter.controller;

import cn.spring.inter.bean.ResponseData;
import cn.spring.inter.entity.TechnologyArticle;
import cn.spring.inter.service.TechnologyArticleService;
import cn.spring.inter.utils.ExchangeConstants;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@RestController
public class TechnologyArticleController {
    @Autowired
    private TechnologyArticleService technologyArticleService;

    @RequestMapping(value = "/v1/technologyArticle", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseData getAll(
            @RequestParam(value = "start", required = false, defaultValue = "0") Integer start,
            @RequestParam(value = "dataLength", required = false, defaultValue = "100") Integer dataLength,
            @RequestParam(value = "sort", required = false, defaultValue = "desc") String sort
    ) {
//        System.out.println("start="+start+"/dataLength="+dataLength);
        ResponseData responseData = new ResponseData();
        JSONObject jsonResultObject = new JSONObject();
        responseData.setCode("200");
        responseData.setStatus("success");
        responseData.setMessage("tenantMessage");
        responseData.setDetail("添加tenantMessage");
        List<TechnologyArticle> technologyArticleList = technologyArticleService.selectAll(start, dataLength, sort);

//        String oldDateStr = "2021-01-26T22:52:00.000+0000";
//        String dateStrNew = ExchangeConstants.dealDateFormat(oldDateStr);
//        System.out.println("dateStrNew == " + dateStrNew);

        List<JSONObject> objTechnologyArticleList = new ArrayList<>();

        for(TechnologyArticle technologyArticle: technologyArticleList){
            JSONObject objTechnologyArticle = new JSONObject();
            System.out.println(technologyArticle.getCreateDate());
//            System.out.println(ExchangeConstants.dealDateFormat());
//            objTechnologyArticle.put("createDate", );
//            objTechnologyArticleList.add(objTechnologyArticle);
        }

        jsonResultObject.put("technology", objTechnologyArticleList);

        responseData.setData(jsonResultObject);
        return responseData;
    }
}



package cn.spring.inter.entity;

import cn.spring.inter.utils.ExchangeConstants;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Entity
@Table(name = "technology_article")
public class TechnologyArticle {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "userID")
    private int userID;

    @Column(name = "content")
    private String content;

    @Column(name = "create_date")
    private Timestamp createDate;

    @Column(name = "update_date")
    private Timestamp updateDate;

    @Column(name = "tags")
    private String tags;

    @Column(name = " qr_code_path")
    private String qrCodePath;

    @Column(name = "url")
    private String url;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }

    public Timestamp getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Timestamp updateDate) {
        this.updateDate = updateDate;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }

    public String getQrCodePath() {
        return qrCodePath;
    }

    public void setQrCodePath(String qrCodePath) {
        this.qrCodePath = qrCodePath;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

解决方案

for(TechnologyArticle technologyArticle: technologyArticleList){
            JSONObject objTechnologyArticle = new JSONObject();
//            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getCreateDate()));
//            System.out.println(ExchangeConstants.dealDateFormat());
            objTechnologyArticle.put("id", technologyArticle.getId());
            objTechnologyArticle.put("title", technologyArticle.getTitle());
            objTechnologyArticle.put("content", technologyArticle.getContent());
            objTechnologyArticle.put("qrCodePath", technologyArticle.getQrCodePath());
            objTechnologyArticle.put("url", technologyArticle.getUrl());
            objTechnologyArticle.put("tags", technologyArticle.getTags());
            objTechnologyArticle.put("createDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getCreateDate()));
            objTechnologyArticle.put("updateDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(technologyArticle.getUpdateDate()));
            objTechnologyArticleList.add(objTechnologyArticle);
        }
阅读 2.6k
2 个回答

首先,通过打印(System.out.println)输出到屏幕上的内容实际上调用了 TimestamptoString() 方法。通过查看其源码,我们可以发现已经被重写过了(所以打印出来是不一样的):

@SuppressWarnings("deprecation")
public String toString() {
    int year = super.getYear() + 1900;
    int month = super.getMonth() + 1;
    ...
    char[] buf = new char[25 + yearSize - trailingZeros];
    Date.formatDecimalInt(year, buf, 0, yearSize);
    buf[yearSize] = '-';
    Date.formatDecimalInt(month, buf, yearSize + 1, 2);
    ...
}

其次楼主确实是想把 2021-01-26T22:52:00.000+0000 给转成 2021-01-27 10:52:00 的话,可以采用如下写法:

Timestamp ts = new Timestamp(new Date().getTime()); //2021-01-27 15:05:07.724 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.format(ts)); //2021-01-27 15:05:07

但是如果出现跨时区使用的话,还需要注意下时区问题。

推荐问题
宣传栏