代码之家  ›  专栏  ›  技术社区  ›  Jus10

Firestore查询日期范围

  •  0
  • Jus10  · 技术社区  · 7 年前

    {
      start: March 5
      end: April 7
    }
    

    例如,我试图找出如何构建一个查询来返回覆盖特定日期的所有事件 March 27 ,就像。。。。

    这样的查询 get all documents whose starting date is before march 27th, and the ending date is after march 27th 但由于Firestore查询的限制,这似乎不可能实现。

    所以我花了好几个小时来挠头,要么为此构建一个查询,要么以某种允许的方式构造数据。

    这可能吗?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Haji Fernandez    7 年前

    从上面的代码保存我的一天。我知道这种代码结构很奇怪,但它很有效。

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Manila"));
        Date newDate = null;
        Date newDate1 = null;
        try {
            newDate = sdf.parse(YOUR_EDIT_TEXT + " 00:00:00");
            newDate1 = sdf.parse(YOUR_EDIT_TEXT + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
    
        db.collection("sales")
                .whereGreaterThanOrEqualTo("created_at", newDate)
                .whereLessThan("created_at", newDate1)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        for(final DocumentSnapshot sales: task.getResult()) {
                            // Do what ever you want with the data.
                        }
                    }
                });
    
        2
  •  0
  •   Abhi    7 年前

    只需使用小于或大于该查询。例如,在我的android For snapshot listener(监听更新)应用程序中,我做了如下操作:

        ListenerRegistration registration;
        String lessDate = "09/04/2019 23:59:59";
        String greaterDate = "11/04/2019 23:59:59";
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss", Locale.getDefault());
        try {
            Date lDate = dateFormat.parse(lessDate);
            Date gDate = dateFormat.parse(greaterDate);
            Query q = db.collection("collection").whereGreaterThan("createdAt", new Timestamp(lDate))
                    .whereLessThan("createdAt", new Timestamp(gDate));
            registration = q.addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.i("FIRESTORE ERROR", "Listen failed.", e);
                        return;
                    }
                    for (DocumentChange doc : value.getDocumentChanges()) {
                        // What ever you want to do.
                    }
                }
            });
        } catch (ParseException e) {
            e.printStackTrace();
        }
    

    对于日期,您实际上可以从系统中获取日期,或者从用户那里获取输入并根据需要进行自定义。如果你需要帮助,请告诉我。