在 android studio 中,我尝试使用内部存储将日历视图的输入保存为 LocalDateTime 作为 Json,但我遇到了问题。我创建了 calenderView 并对其进行了设置,以便当您通过用户界面更改它时它会获取日期,如下所示。
CalendarView dateInput = findViewById(R.id.calenderDate);
dateInput.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
inputtedDate = LocalDate.of(year, month + 1, dayOfMonth);
}
});
然后我从包含用户输入时间的文本框中获取字符串,然后使用 .of 方法将它们组合在一起作为一个 DateTime。
String timeString = timeInput.getText().toString();
LocalTime inputtedTime = LocalTime.parse(timeString);
LocalDateTime inputtedDateTime = LocalDateTime.of(inputtedDate, inputtedTime);
然后使用 Gson 将其保存到内部存储。
public void WriteJsonToStorage(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(bookingToWrite);
FileOutputStream fos = null;
fos = context.openFileOutput("SingleBooking.txt", Context.MODE_PRIVATE);
fos.write(json.getBytes());
}
在调试器中,我可以看到,当我选择日期并将超时手动写入“14:56”时,它会拾取该内容
2023-12-14T14:56
但是当我检查文件后,我检查的日期时间中没有任何内容。
{
"bookingDateTime": {},
"bookingName": 0,
"peopleTotal": 5,
"tableNumber": 0
}
我这里缺少一个步骤,以便它可以正确地将日期和时间存储在 json 中吗?
如果您想获取具有区域设置的特定模式的日期和时间,您可以使用以下命令:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault());
String currentDateandTime = sdf.format(new Date());