如何将Date(以毫秒为单位)转换为Date,就像在数据库中一样?

时间:2013-01-17 22:21:41

标签: java date timestamp

我有@Entity字段

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_on", nullable = false)
    private Date createdOn;

将时间戳保存为

+----+------+------------+-------+--------------------------+---------------------+---------------------+------+
| id | name | type       | units | description              | created_on          | retired_on          | core |
+----+------+------------+-------+--------------------------+---------------------+---------------------+------+
|  1 | v1   | Double     | u1    | created via migration    | 2013-01-14 13:15:19 | NULL                |    1 |
|  2 | v2   | String     | u2    | created via migration    | 2013-01-14 13:15:19 | NULL                |    1 |
|  3 | v3   | BigDecimal | u3    | created via migration    | 2013-01-14 13:15:19 | NULL                |    0 |
| 27 | v4   | String     | u4    | created with web service | 2013-01-15 10:37:30 | 2013-01-15 11:27:48 |    1 |
+----+------+------------+-------+--------------------------+---------------------+---------------------+------+

当我检索数据时,我得到Date对象,其值为

"createdOn": 1358198119000,
"createdOn": 1358198119000,
"createdOn": 1358198119000,
"createdOn": 1358275050000, 

如何将它们转换回日期时间戳,如'2013-01-15 10:37:30'而不是数字1358198119000

2 个答案:

答案 0 :(得分:0)

此值仅仅是几天以来的几秒,它们仍然代表正确的Date个对象。什么对你的“时间戳”有意义?作为Timestamp java类实例还是只有有效格式?

这样的事情可以帮助第一个问题回答:

java.sql.Timestamp timestamp = new java.sql.Timestamp(createdOn.getTime());

这样的事情可能有助于第二个问题回答“是”:

SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestampedDate = formater.format(createdOn);

答案 1 :(得分:0)

将您的TemporalType更改为DATE

@Temporal(TemporalType.DATE)
@Column(name = "created_on", nullable = false)
private Date createdOn;