问题描述
我有一个具有以下结构的模型
I have a model with the following structure
public class OfferModel {
private String mImageUrl;
private String mOfferCode;
private String mOfferTitle;
private String mOfferDescription;
private boolean mIsRunning;
private String mCreatorUid;
private Date mStartDate;
}
保存时其他一切正常。它在Firebase实时数据库中保存为
Everything else works fine on saving. It saves in Firebase Realtime database as
startDate
date: 22
day: 3
hours: 23
minutes: 20
month: 5
seconds: 50
time: 1466617850476
timezoneOffset: -330
year: 116
但是当我尝试检索它时,日期会出现以下错误 -
But when I try to retrieve it, the date gives the following error -
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Date
at com.localvine.models.OfferModel.<init>(OfferModel.java:37)
at com.localvine.managers.OfferManager$1.onDataChange(OfferManager.java:62)
at com.google.android.gms.internal.zzafp.zza(Unknown Source)
at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
at com.google.android.gms.internal.zzags$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:615)
我知道Firebase没有不支持Java Date对象,但是罪恶如果它将它们保存在地图中,我该如何从该地图中取回日期?在Firebase Android中是否有正确的保存和检索日期的方法?
I understand that Firebase doesn't support Java Date object, but since it's saving them in a map, how can I get back the date from that map? Is there any proper way of saving and retrieving dates in Firebase Android?
推荐答案
您可以将日期存储为纪元日期。您可以使用系统时间 System.currentTimeMillis();
或使用Firebase服务器时间及其 ServerValue.TIMESTAMP
。第一个选项是它随时区和系统设置而变化。因此,如果您将日期存储为长,则只需将 OfferModel
字段 mStartDate
更改为 long
然后使用 new Date(long)
获取相应的日期
检索对象时。
You can store the date as an epoch date. It's a long that you can get using your system time System.currentTimeMillis();
or by using the Firebase server time with their ServerValue.TIMESTAMP
. The thing with the first option is that it changes with timezones and system settings. So if you store the date as a long, you just have to change your OfferModel
field mStartDate
to a long
and then use new Date(long)
to get the corresponding Date
when retrieving the object.
这篇关于在Firebase中保存和检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!