【发布时间】:2021-12-31 07:06:16
【问题描述】:
我正在使用日期选择器和时间选择器对话框来选择要保存到 Firestore 文档中的日期和时间。我还使用 java 的 LocalDateTime 在本地存储我从选择器对话框中选择的日期和时间。将我为Map<String, Object> 创建的LocalDateTime 变量放入Firestore,将日期和时间保存为Map 字段,而不是时间戳字段。我在这个网站上看到了一个类似的问题,但解决方案是使用LocalDateTime 的前身Date。我不打算用旧版本替换 LocalDateTime 只是为了实现我想要做的事情。如果你们知道如何使用LocalDateTime 将日期和时间存储到 Firestore。
LocalDateTime 初始化:
LocalDateTime localDateTime = LocalDateTime.now();
int yr = localDateTime.getYear();
int mos = localDateTime.getMonthValue();
int dy = localDateTime.getDayOfMonth();
int hr = localDateTime.getHour();
int min = localDateTime.getMinute();
日期和时间选择器对话框:
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
TimePickerDialog timePickerDialog = new TimePickerDialog(DateTimeChoose.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
localDateTime = LocalDateTime.of(year, month+1, day, hour, minute);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("'Elections Will End On:\n'MMM dd, yyyy'\n@ 'hh:mm a");
electionsText.setText(dateTimeFormatter.format(localDateTime));
}
}, hr, min, false);
timePickerDialog.show();
}
}, yr, mos-1, dy);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
将日期和时间存储到 Firestore:
CollectionReference admin = FirebaseFirestore.getInstance().collection("Admin");
Map<String, Object> electionEndTime = new HashMap<>();
electionEndTime.put("electionEndTime", localDateTime);
admin.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String adminEmail = "";
List<DocumentSnapshot> documentSnapshots = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot documentSnapshot : documentSnapshots) {
adminEmail = documentSnapshot.getId();
}
admin.document(adminEmail).set(electionEndTime, SetOptions.merge());
}
});
【问题讨论】:
-
为什么不使用Date 对象?
-
很高兴在这里见到你 @AlexMamo 先生。并不是我不想使用 Date 对象。我只想知道是否有办法使用用户友好的
java.time来放置时间戳。如果没有办法做到这一点,那么使用 Date 对象是我的替代选择。
标签: java android firebase google-cloud-platform google-cloud-firestore