San*_*ngh 4 android google-cloud-firestore
我试图使用EditText和DateTimePicker对话框在firestore数据库上保存日期.问题是,日期被存储为服务器上的字符串.如果我使用FieldValue.serverTimestamp()它只保存字段中的服务器时间戳,但我想将DateTimePicker对话框返回的日期保存为时间戳.
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);
}
});
Run Code Online (Sandbox Code Playgroud)
日期将存储为字符串:
您可以将Date对象保存为您的案例中的时间戳,您可以将字符串解析为日期对象并将其直接保存为firestore文档中的字段,例如,您可以执行以下操作: -
first:将有效日期字符串转换为日期对象
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 ;
}
}
Run Code Online (Sandbox Code Playgroud)
然后将日期对象保存为firestore文档中的字段
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);
}
Run Code Online (Sandbox Code Playgroud)
您可以选择任何其他格式以获取更多信息,以检查如何解析日期以及java.util.Date对象的工作方式.
如果运行上面的代码,日期将在firestore文档中保存为Timestamp
| 归档时间: |
|
| 查看次数: |
3733 次 |
| 最近记录: |