如何更改 json 日期字符串并将其格式化为仅显示没有年、月或时间的日期

How to change json string of date and format it to only show the day without, year, month, or time

我有一个 JSONObject 和一个 ArrayList,我从那里获取数据,我获取的数据日期字符串是 yyyy/MM/dd 00:00:00,我只想显示月份 1-31 的日期,我如何格式化该字符串以仅显示日期?

我试过使用 SimpleDateFormat,但没有成功,可能是因为我是在 for 循环中这样做的?

public void onResponse(String response) {

                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);

                            ArrayList<ListModel> ListModelArrayList = new ArrayList<>();
                            JSONArray dataArray = obj.getJSONArray("events");

                            for (int i = 0; i < dataArray.length(); i++) {

                                ListModel List = new ListModel();
                                JSONObject dataobj = dataArray.getJSONObject(i);

                                List.setId(dataobj.getString("id"));
                                List.setInit_date(dataobj.getString("init_date"));
                                List.setEnd_date(dataobj.getString("end_date"));
                                List.setTitle(dataobj.getString("title"));
                                List.setDescription(dataobj.getString("description"));
                                List.setColor_code(dataobj.getString("color_code"));
                                List.setAll_day(dataobj.getString("all_day"));

                                ListModelArrayList.add(List);
                            }

                            for (int j = 0; j < ListModelArrayList.size(); j++) {

                                textViewDate.setText(textViewDate.getText() +
                                        ListModelArrayList.get(j).getInit_Date() + "\n");


                                textViewEvent.setText(textViewEvent.getText() +
                                        ListModelArrayList.get(j).getTitle() + "\n");

                            }

现在我正在获取这种格式 2019-05-17 00:00:00,我只想显示 17

您可以按照您的建议更改 SimpleDateFormat,而不是将日期直接放在此处的 for 循环中:

textViewDate.setText(textViewDate.getText() +
                                    ListModelArrayList.get(j).getInit_Date() + "\n");

您将在循环中执行以下操作:

String s = ListModelArrayList.get(j).getInit_Date();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
    Date date = null;
    try {
        date = fmt.parse(s);
        SimpleDateFormat fmtOut = new SimpleDateFormat("dd", Locale.ENGLISH);

        textViewDate.setText(textViewDate.getText() +
                fmtOut.format(date) + "\n");
    } catch (ParseException e) {
        textViewDate.setText(textViewDate.getText() + "\n");
        e.printStackTrace();
    }

这允许您在这一行中根据您希望的模式设置日期格式:

 SimpleDateFormat fmtOut = new SimpleDateFormat("dd", Locale.ENGLISH);

模式参考 Oracle Documentation SimpleDateFormat Patterns