gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:23:38 25 4
gpt4 key购买 nike

我有一个 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

关于java - 如何更改日期的 json 字符串并将其格式化为仅显示日期而不显示年、月或时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com