Parse JSON in UNIX date in Java/Android without any library

前端 未结 3 1156
鱼传尺愫
鱼传尺愫 2021-01-07 12:39

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

相关标签:
3条回答
  • 2021-01-07 13:37

    I have checked your api documentation and the date you have in response is in unix time format as described here wall.post

    You can convert it using the method described here Convert Unix time stamp to date in java

    Once converted you can format the date as described below.

     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);
    
    0 讨论(0)
  • 2021-01-07 13:38

    I don't really understand what you are trying to ask here. But if you're asking is to ow to convert that date that you get in human readable form then you should take a look at Epoch Converter. The date is returned to you in epoch timestamp. You can convert the same to a human readable form n java by using the following code.

    String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
    
    0 讨论(0)
  • 2021-01-07 13:43

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

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

    0 讨论(0)
提交回复
热议问题