【问题标题】:mysql timestamp displaying in seconds - how to display in javamysql时间戳以秒为单位显示-如何在java中显示
【发布时间】:2015-09-01 11:43:18
【问题描述】:

存储在 MySQL 数据库中的时间戳 '2015-06-15 13:01:48' 在我的 rest 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 视图:

@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);
    }
}

【问题讨论】:

  • 你是在使用Jackson进行序列化吗?如果是,哪个版本?
  • 是的,使用 Jackson 2.3.3 版

标签: java mysql hibernate rest


【解决方案1】:

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;

不过,请仔细检查模式,我不能 %100 确定它是否正确。与 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}

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

【讨论】:

  • 这不起作用! PS:哎呀!为了隐藏真实姓名,我输入了大写字母。
猜你喜欢
  • 2014-08-31
  • 2021-11-20
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多