在特定日期后如何删除Firebase数据库上的子节点?

时间:2018-10-20 11:12:45

标签: java android firebase firebase-realtime-database

如果值(日期)<当前时间日期,则需要删除子项(邮政编码)

这是我的数据库的样子: database

 Calendar calFordDate;
        calFordDate = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
        String CurrentDate = currentDate.format(calFordDate.getTime());
        PostsRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String tripdate = dataSnapshot.child(postkey).child("date").getValue().toString();
                if(CurrentDate.after(tripdate)) {

                    dataSnapshot.getRef().removeValue();
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

2 个答案:

答案 0 :(得分:1)

您的答案中的错误是由于tripdate是字符串而不是Date对象。要将字符串转换为日期,您可以使用如下代码:

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

还要在不知道值的情况下从Firebase数据库中删除子级,还必须使用类似以下代码的代码:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query delQuery = ref.child("Posts").orderByChild("date").equalTo(DateYouKnowIsThere);

delQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot dSnapshot: dataSnapshot.getChildren()) {
            dSnapshot.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});

答案 1 :(得分:0)

我使用了这段代码,并没有在旧的子节点达到当前日期(CurrentDate)时删除

       Calendar calFordDate;
       calFordDate = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        String CurrentDate = format.format(calFordDate.getTime());

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Query delQuery = ref.child("Posts").orderByChild("date").equalTo(CurrentDate);


        delQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot dSnapshot: dataSnapshot.getChildren()) {
                    dSnapshot.getRef().removeValue();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });