如何在JSON对象中格式化此Date

时间:2021-05-11 16:50:55

I have this date in json

我在json有这个约会

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

And I want to convert it to 29 Jan, 2016

我想将其转换为2016年1月29日

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)

在postItem.setPost_date(date)中;日期用红色加下划线,当我将鼠标悬停时,我看到PostItems中的setPost_date(java.lang.String)无法应用于(java.util.Date)

Anyway to properly format this?

无论如何要正确格式化这个?

1 个解决方案

#1


1  

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

#1


1  

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