0

I wrote a program to remove post from firebase. When currentDate == reference ("post"). Child (postKey) .child ("date") then post should be deleted. check passes each (new Thread) 24 hours I can’t understand why he doesn’t get post

private void deletePostFromFirebase(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(true) {
                try {
                    Thread.sleep(1000L*60L*60L*24L);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
                    Date date = new Date();
                    String newDate = simpleDateFormat.format(date);
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
                    ref.orderByChild("date").equalTo(newDate).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            for (DataSnapshot itemSnapshot : dataSnapshot.getChildren()) {
                                itemSnapshot.getRef().removeValue();
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });
                }catch (InterruptedException e){
                    showMessage(e.getMessage());
                }
            }
        }
    }).start();
}

I think that the date written in firebase (post.child -> date ' 30 апр 2020') is written in Russian format, and the current date that I get is written currentDate'30 april 2020 'english format. I think that this is a problem. Can someone explain this to me or is there another problem.

enter image description here

1 Answers1

0

If you want to be able to order/filter by date, you need to ensure that those dates are stored in a format that can be ordered/filtered.

The toString() representation that you use for dates is not such a format, since its lexicographical/alphabetical sort order is different from its chronological sort order. Some examples may make this clear:

  • In lexicographical order 30 January comes after 28 February, because 3 > 2.
  • In lexicographical order January 30 comes after February 28, because J > F.

Proper formats for storing dates so that you sort/filter them are:

  • Storing them as timestamps, which is the count of milliseconds that have passed since the epoch. Since these are numerical values, they can be sorted and compared numerically, instead of lexicographically.
  • Storing them in a string format where the lexicographical order is the same as the chronological order, for example: "2020-04-16". Because "2020-01-30" < "2020-02-28".

For more on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807