将Meteor.js DDP日期转换为Java Date

时间:2015-03-29 02:29:50

标签: java android json date ddp

我正在使用Android DDP Client库将我的Android客户端连接到Meteor-JS服务器。当我收到一个新对象时,我使用以下代码来解析" createdAt"字段

private Map<String, Object> fields;
private Date timestamp;
/*...*/
timestamp = (Date) fields.get("createdAt");

我错误地认为它应该是Date类型。我收到一条错误消息:

com.google.gson.internal.LinkedHashTreeMap cannot be cast to java.util.Date

如何正确解析Meteor发送的日期?

1 个答案:

答案 0 :(得分:0)

Meteor-JS向您发送JSON。

// The Date value in the JSON response is a Unix timestamp.
// It gives the number of milliseconds since 1 January 1970 00:00:00 UTC.
// So we can do:
Double jsonDate = ((Map<String, Double>) fields.get("createdAt")).get("$date");
timestamp = new Date(jsonDate.longValue());

ps。我建议将时间戳存储为long字段,而不是Date