Java 在 Firebase 中保存和检索日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37976468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:52:03  来源:igfitidea点击:

Saving and retrieving date in Firebase

javaandroiddatefirebase

提问by noob

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.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.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?

我知道 Firebase 不支持 Java Date 对象,但由于它将它们保存在地图中,我怎样才能从该地图中取回日期?在 Firebase Android 中是否有任何正确的方法来保存和检索日期?

采纳答案by Sunshinator

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 OfferModelfield mStartDateto a longand then use new Date(long)to get the corresponding Datewhen retrieving the object.

您可以将日期存储为纪元日期。您可以使用系统时间System.currentTimeMillis();或将 Firebase 服务器时间与它们的ServerValue.TIMESTAMP. 第一个选项是它会随着时区和系统设置而变化。因此,如果您将日期存储为 long,则只需将您的OfferModel字段更改mStartDate为 a long,然后在检索对象时使用new Date(long)以获取相应Date的。

回答by Zack

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 上的显示方式:

Date onFirebase

Firebase 上的日期

Hope it helps..

希望能帮助到你..

回答by yading

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

我注意到日期的其他问题,当我从数据库手动更改月份时,检索它时,该值保持不变

回答by Nabajyoti Das

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 确实支持日期格式数据类型,但我更愿意以字符串格式保存日期时间,因为通过将其存储为字符串,检索它变得非常容易。

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 中或对该字符串做任何想做的事情。

回答by JP Ventura

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 Dateas a Stringhas two greater advantages:

表示Date为 aString有两个更大的优点:

  • It is human readable ("2018-03-30T13:18:39.516Z"vs 1522415925281)
  • At the browser side, you can simply invokes new Date("2018-03-30T13:18:39.516Z")
  • 它是人类可读的("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.

如果您的 Android 和浏览器都使用 Firebase 数据,这将非常有用。