androidjsondatetimeandroid-parser

Json DateTime Parsing In Android


My API Gives This Result:

{
    "Posts": [{
        "UseName": "Robert Ray",
        "DateTime": "\/Date(1376841597000)\/",
        "PostText": "Welcome!!\u003cbr\u003eThis Is my Text"
    }]
}

I Parse My JSON Like This

try {
    Posts = json.getJSONArray(TAG_POSTS);

    for(int i = 0; i < Posts.length(); i++){
        JSONObject c = Posts.getJSONObject(i);
        String post_text = c.getString("PostText"); 

        String strDate = "2013-05-15T10:00:00-0700";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        Date date = (Date) dateFormat.parse(c.getString("DateTime"));
    }
} catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
} catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
} 

But Its Not Working, what I want is It should calculate the time elapsed since the User posted the Post,
i.e we have to subtract the current data with the date in JSON, and then convert that in Minutes / Hours


Solution

  • Well I hope that you find this usefull:

    String ackwardDate = "/Date(1376841597000)/";
    //Dirty convertion
    Calendar calendar = Calendar.getInstance();
    String ackwardRipOff = ackwardDate.replace("/Date(", "").replace(")/", "");
    Long timeInMillis = Long.valueOf(ackwardRipOff);
    calendar.setTimeInMillis(timeInMillis);
    System.out.println(calendar.getTime().toGMTString()); //Prints 18 Aug 2013 15:59:57 GMT
    

    But I'm saying, that date format in your JSON It's really ackwards, take the example of google, for a correct, standar, parsed JSON.