简体   繁体   中英

How to format this Date in JSON object

I have this date in json

"date": "2016-01-29T19:27:44",

And I want to convert it to 29 Jan, 2016

Currently I am usin this code to do the formatting:

private void parseData(JSONArray array){
    Log.d(TAG, "Parsing array");

    for(int i = 0; i<array.length(); i++) {
        PostItems postItem = new PostItems();
        JSONObject jsonObject = null;
        try {
            jsonObject = array.getJSONObject(i);
            postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
            postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));

            SimpleDateFormat formatDate = new SimpleDateFormat("dd MMM,yyyy");
            String postDate = jsonObject.getString(ConfigPost.TAG_POST_DATE);
            try {
                Date date = formatDate.parse(postDate);
                postItem.setPost_date(date);
            } catch (ParseException e) {
                Log.d(TAG, "Error in Parsing date");
            }



        } catch (JSONException w) {
            w.printStackTrace();
            //Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
        }
        mPostItemsList.add(postItem);
    }

}

In line postItem.setPost_date(date) ; date is underlined in red and when I hover it, I see setPost_date (java.lang.String) in PostItems cannot be applied to (java.util.Date)

Anyway to properly format this?

SimpleDateFormat formatDate = new SimpleDateFormat("dd MMM,yyyy");
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String inputDateStr = jsonObject.getString(ConfigPost.TAG_POST_DATE);
try {
    Date inputDate = inputFormat.parse(inputDateStr);             
    String postDateStr = formatDate.format(inputDate); 
    postItem.setPost_date(postDateStr);
} catch (ParseException e) {
     Log.d(TAG, "Error in Parsing date");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM