【问题标题】:Parse JSON in UNIX date in Java/Android without any library在没有任何库的情况下在 Java/Android 中解析 UNIX 日期中的 JSON
【发布时间】:2014-12-08 17:03:43
【问题描述】:

我从我的服务器收到了一个 JSON 数组。我以时间戳字符串的形式获取日期——例如,[{"date": "1418056895", ... }]——我需要以我们的日期格式对其进行解析。我该怎么做呢?我试过了,但我总是把年份设为 1970。

注意:我的 JSON 格式是 UNIX。

JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setTimeStamp(feedObj.getString("date"));


public void setTimeStamp(String timeStamp) {
    this.timeStamp = timeStamp;
}

public String getTimeStamp() {
    return timeStamp;
}

在另一个类中,我解析时间戳以显示它:

List<FeedItem> feedItems = ...;
FeedItem item = feedItems.get(position);
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(item.getTimeStamp()),
           System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);

但是显示的日期始终是 1970 年。

使用诸如1403375851930 之类的值,它似乎可以按预期工作(它显示一个当代日期)。

【问题讨论】:

  • 你为什么用getRelativeTimeSpanString
  • 我想转换成人类可读的格式
  • 教程里不知道是不是
  • 究竟是什么不起作用?你有什么问题?
  • 我得到了这个数据,所以我想像 8.12.2014 一样转换它,但是当我从 Json 得到它时,它的日期很相似“:1418056895

标签: java android json


【解决方案1】:

如果你正确解析 JSON,

feedObj.getString("date");

保留您的日期。您正在将日期读取为字符串。您必须将其转换为 long。

public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    Long timestamp = Long.parseLong("1418056895"); //Long.parseLong(feedObj.getString("date"));
    cal.setTimeInMillis(timestamp * 1000L);
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); // what ever format you need.
    System.out.println(format.format(cal.getTime())); // this will be in MM/dd/yyyy
    //item.setTimeStamp(format.format(cal.getTime()));
}

您也可以使用 feedObj.getLong("date");直接获取长格式的日期,但这取决于您使用的 JSON 库。

【讨论】:

  • 你是最好的非常感谢你
【解决方案2】:

我真的不明白你想在这里问什么。但是,如果您要求将获得的日期转换为人类可读的形式,那么您应该查看Epoch Converter。日期以纪元时间戳返回给您。您可以使用以下代码将其转换为人类可读的形式 n java。

String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

【讨论】:

  • 如何配合json使用
【解决方案3】:

我检查了您的 api 文档,您的回复日期采用 unix 时间格式,如此处所述wall.post

您可以使用这里描述的方法Convert Unix time stamp to date in java进行转换

转换后,您可以按如下所述格式化日期。

 private List<FeedItem> feedItems;
TextView timestamp
 FeedItem item = feedItems.get(position);
Long timeObject = Long.parseLong(getTimeStamp());

//use the timeObject and convert it in the String as described
// in above link to convert timestamp in date object than in String

//Once available set it again in timestamp
timestamp.setText(formattedDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2011-06-28
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多