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; }
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)
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?
Go to the Firebase Console, select your project and click on the Database tab. Scroll down and you will find a Realtime Database section. Click on Create database, select the Start in test mode option and then click Enable.
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 .
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
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.
Use ISO 8601 date format:
SimpleDateFormat ISO_8601_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss'Z'"); String now = ISO_8601_FORMAT.format(new Date());
Representing Date
as a String
has two greater advantages:
"2018-03-30T13:18:39.516Z"
vs 1522415925281
)new Date("2018-03-30T13:18:39.516Z")
This is quite useful if you have Android and browsers both consuming Firebase data.
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