在UNIX日期的Java / Android的解析JSON没有任何图书馆 [英] Parse JSON in UNIX date in Java/Android without any library

查看:127
本文介绍了在UNIX日期的Java / Android的解析JSON没有任何图书馆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器接收到的JSON数组。我得到一个日期作为时间戳记字符串&ndash的;例如, [{日期:1418056895,...}] &ndash的;我需要解析它在我们这个时代的格式。我该怎么做呢?我曾经试过,但我总是有一年,1970年。

I have a JSON array received from my server. I obtain a date as a timestamp String – for example, [{"date": "1418056895", ... }] – and I need to parse it in our day format. How do I do this? I have tried but I always have the year as 1970.

注:我的JSON格式是UNIX

Note: My JSON format is in 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;
}

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

In another class, I parse the timestamp to display it:

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

不过显示的日期始终是在1970年。

However the displayed date is always in 1970.

使用的值,如 1403375851930 它似乎按预期(它会显示一个当代的日期)。

Using values such as 1403375851930 it appears to work as expected (it displays a contemporary date).

推荐答案

如果您正确解析JSON,

If you are parsing JSON correctly,

feedObj.getString("date");

握着你的日期。您正在阅读的日期字符串。你必须将其转换为长。

holds your date. You are reading date as String. You have to convert it to 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(日);获得长格式的日期直接,但它取决于你使用哪个JSON库。

you can also use feedObj.getLong("date"); to get Date in long format directly, but it depends on which JSON library you using.

这篇关于在UNIX日期的Java / Android的解析JSON没有任何图书馆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆