I am using a date picker and time picker dialog to choose what date and time to save into a Firestore document. I am also using java's LocalDateTime
to store locally what date and time I picked from the picker dialogs. Putting the LocalDateTime
variable that I created for the Map<String, Object>
and saving it into Firestore, saves the date and time as a Map
field, and not a timestamp field. I saw a similar question here at this website but the solution is using LocalDateTime
's predecessor, Date
. I am not planning to replace LocalDateTime
with the old version just to achieve what I am trying to do. If you guys know how to store the date and time to Firestore using LocalDateTime
.
LocalDateTime Initialization:
LocalDateTime localDateTime = LocalDateTime.now();
int yr = localDateTime.getYear();
int mos = localDateTime.getMonthValue();
int dy = localDateTime.getDayOfMonth();
int hr = localDateTime.getHour();
int min = localDateTime.getMinute();
Date and Time Picker Dialog:
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();
Storing date and time to 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());
}
});
Screenshot of Firestore document:
CodePudding user response:
You cannot use a LocalDateTime object, as it's not a supported data type. What you can use instead, is a Date object. You can simply write such a value as you already do in your code.