简体   繁体   English

在Firebase中保存和检索日期

[英]Saving and retrieving date in Firebase

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 它将Firebase实时数据库保存为

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? 我了解Firebase不支持Java Date对象,但由于它将它们保存在地图中,我该如何从该地图中取回日期? Is there any proper way of saving and retrieving dates in Firebase Android? 有没有在Firebase Android中保存和检索日期的正确方法?

You can store the date as an epoch date. 您可以将日期存储为纪元日期。 It's a long that you can get using your system time System.currentTimeMillis(); 您可以使用系统时间System.currentTimeMillis(); or by using the Firebase server time with their ServerValue.TIMESTAMP . 或者将Firebase服务器时间与其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. 因此,如果将日期存储为long,则只需将OfferModel字段mStartDate更改为long ,然后使用new Date(long)在检索对象时获取相应的Date

Use ISO 8601 date format : 使用ISO 8601日期格式

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: Date表示为String有两个更大的优点:

  • It is human readable ( "2018-03-30T13:18:39.516Z" vs 1522415925281 ) 它是人类可读的( "2018-03-30T13:18:39.516Z" vs 1522415925281
  • At the browser side, you can simply invokes new Date("2018-03-30T13:18:39.516Z") 在浏览器端,您只需调用new Date("2018-03-30T13:18:39.516Z")

This is quite useful if you have Android and browsers both consuming Firebase data. 如果Android和浏览器都使用Firebase数据,这非常有用。

This is how I managed to store Date on Firebase by using the SimpleDateFormat to convert it to only a date without seconds, hours or milliseconds. 这就是我通过使用SimpleDateFormat将日期转换为没有秒,小时或毫秒的日期来设置在Firebase上存储日期的方法。

public void storeDatetoFirebase() {

    handler = new Handler();

    runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            try {
                Date date = new Date();
                Date newDate = new Date(date.getTime() + (604800000L * 2) + (24 * 60 * 60));
                SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
                String stringdate = dt.format(newDate);

                System.out.println("Submission Date: " + stringdate);
                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("My_Date");
                databaseReference.child("init_date").setValue(stringdate);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    handler.postDelayed(runnable, 1 * 1000);
}

and this is how it appears on Firebase: 这就是它在Firebase上的显示方式:

onFirebase上的日期

Hope it helps.. 希望能帮助到你..

Although firebase does support Date format datatype, I would prefer to save date-time in a string format, because by storing it as a string it becomes quite easy to retrieve it. 尽管firebase支持Date格式数据类型,但我更喜欢以字符串格式保存日期时间,因为通过将其存储为字符串,可以很容易地检索它。

To store current system date-time in a string format just below code will do. 要以字符串格式存储当前系统日期时间,只需在代码下方即可。

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String strDate = dateFormat.format(date).toString();
        myRef.child("datetime").setValue(strDate);   

Now one can use the strDate to store in the firebase or do whatever one want to do with that string. 现在可以使用strDate存储在firebase中,或者做任何想要对该字符串做的事情。

you can set a date object on Firebase 您可以在Firebase上设置日期对象

yourReference.setValue(new Date());

It works, But 它有效,但是

I noticed other PROBLEM with the date, when i changed the month manually from the db, when retrieving it the value stays as before 我注意到其他问题与日期,当我从数据库手动更改月份时,检索它时,值保持不变

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM