存储在 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);
}
}
最佳答案
在实体上尝试用以下方式注释 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/