java - mysql时间戳显示以秒为单位 - 如何在java中显示

标签 java mysql hibernate rest

存储在 MySQL 数据库中的时间戳“2015-06-15 13:01:48”在我的其余 api 响应中为 1434369708000。如何处理以使响应也具有相同的格式。我正在使用 Java、Hibernate、Restful WS 和 MySQL。

实体:

private Date CreatedDateTime;

@Column(name = "created_Date_Time", columnDefinition = "TIMESTAMP")
public Date getCreatedDateTime() {
    return createdDateTime;
}

public void setCreatedDateTime(Date createdDateTime) {
    this.createdDateTime= createdDateTime;
}

JSON View :

@JsonView({MessageView.class})
public Date getCreatedDateTime() {
    if (device != null) {
        return device.getCreatedDateTime();
    }
    return null;
}

public void setCreatedDateTime(Date CurrentServerUTC) {
    if (device != null) {
        this.device.getCreatedDateTime(CurrentServerUTC);
    }
}

最佳答案

http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonFormat.html

在实体上尝试用以下方式注释 CreatedDateTime:

@JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss")
private Date CreatedDateTime;

不过,请仔细检查该模式,我不能百分百确定它是否正确。它与 Java SimpleDatePattern 字符串相同。

PS:Java中非静态字段名称惯例以小写字母开头。

我编写了一个简单的测试来展示此注释:

public class JacksonDateTest {

    @Test
    public void test() throws Exception {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectMapper om = new ObjectMapper();

        om.writeValue(baos, new Sth());

        baos.write("\n Sth2 \n".getBytes());

        om.writeValue(baos, new Sth2());

        System.out.println(baos.toString());

        baos.close();
    }


    public class Sth {
        @JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss")
        Date creationDate = new Date();

        public Date getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }
    }

    public class Sth2 {
        Date creationDate = new Date();

        public Date getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }
    }   
}

它有效。某物序列化为:

 {"creationDate":"2015-06-16 16:09:06"}

而 Sth2 序列化为:

 {"creationDate":1434470946137}

您的代码中肯定还有其他问题。

关于java - mysql时间戳显示以秒为单位 - 如何在java中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871253/

相关文章:

java - 如何避免使用反射来创建新实例

java - 将 UTC 日期转换为不同时区的日期

mysql - 来自单行的 SQL 联合

hibernate - grails 3.3.0 : org. h2.jdbc.JdbcSQLException:在单元测试中找不到表 "XYZ"

java - 为什么随机访问文件在我的 UTF-8 文本文件中读取“ï”作为第一个字符?

java - WebDriver 不接受 Chrome 中的 js 警报

java - JPA + hibernate 外键为空

database - Hibernate:LEFT JOIN FETCH 具有用于连接的多列

mysql - 使用 JOIN 而不是 WHERE OR... IN 子查询

mysql - 检查数据库行中是否匹配 3 个或更多匹配项