javaandroidfirebasefirebase-realtime-database

Android Firebase TIMESTAMP


Button with onClickListener to post the TIMESTAMP in child("Date")

users.child(user.getUid()).child("Date").setValue(ServerValue.TIMESTAMP);

It works fine.

My problem is when I try to retrieve in my APP on the phone, I'm getting the current time not the actual TIMESTAMP time .

 users.child(user.getUid()).child("Date").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Date date=new Date();
                SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
                sfd.format(new Date());



                TimeSold.setText(String.valueOf(date));


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

The TIMESTAMP is changing on Firebase and it should be different from user to other. On my App it just gives me the same current time for all users.

My Firebase

enter image description here


Solution

  • If the timestamp is saved as a Long value, put:

    Date date = new Date(dataSnapshot.getValue(Long.class));
    SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", 
                                        Locale.getDefault());
    String text = sfd.format(date);
    TimeSold.setText(text);
    

    in the onDataChange callback

    Your solution is not working because you're passing the current date to the format, as you wrote down:

    Date date = new Date()
    

    By default it takes the local current time.