I was trying to save date on firestore database using EditText and DateTimePicker Dialog. The Problem is, date is getting stored as string on server. If I use the FieldValue.serverTimestamp()
it only saves the server timestamp in the field but I want to save the date returned by DateTimePicker dialog as timestamp.
FirebaseFirestore db2 = FirebaseFirestore.getInstance();
Map<String, Object> addAnimal = new HashMap<>();
addAnimal.put("dob", editText.getText());
db.collection("users").document("animals")
.set(addAnimal)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
The Date is getting stored as string:
you can save Date object as timestamp in your case , you can parse the string to date object and save it directly as field in firestore document , for example you could do something like this :-
first : convert the valid date string to date object
static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public Date getDateFromString(String datetoSaved){
try {
Date date = format.parse(datetoSaved);
return date ;
} catch (ParseException e){
return null ;
}
}
then save the date object as field in firestore document
public void savetoDatabase(){
FirebaseFirestore db = FirebaseFirestore.getInstance();
Map<String,Object> addAnimal = new HashMap<>();
addAnimal.put("dob",getDateFromString("2017-10-15T09:27:37Z"));
db.collection("users").document("animals").set(addAnimal);
}
you can choose any other format for more info check how to parse dates and how the java.util.Date object works .
if you runs the above code the date will saved as Timestamp in firestore document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With