Ayman.dev
Ayman.dev

Reputation: 81

How to fix timestamp java + firestore problems?

i'm creating an chat app depending on firestore and java android ,sorting the chat by timestamp depending on https://firebase.google.com/docs/reference/android/com/google/firebase/Timestamp

but sorting is every time depends on device time even if the time on device is wrong,this disappoint me,please help!!


my code for upload timestamp:

Timestamp dd= Timestamp.now();
long tt=dd.getSeconds();
        hashMap.put("ServerTimes",tt);

my code for download timestamp:

@Override
    public void onBindViewHolder(@NonNull final MessageAdapter.ViewHolder holder, int position) {

Chat chat = mChat.get(position);
       long date = (long) chat.getServerTimes();

        Date date3 = new Date ();
        date3.setTime(date*1000);


        SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy EEE");
        SimpleDateFormat format2 = new SimpleDateFormat("h:mm:s a");

        String dateDisplay1 = format1.format(date3);
        String dateDisplay2 = format2.format(date3);
String DateTime= dateDisplay1+" -- "+dateDisplay2;

My code for sorting:

  private void readMessages(final String myEmail, final String OtherUserEmail, final String imageUrl) {
            final List<Chat> mChat = new ArrayList<>();
    referenceContent.orderBy("ServerTimes", Query.Direction.ASCENDING) .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
................

Upvotes: 0

Views: 289

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

If you don't want to rely on the client-side timestamp, you can tell Firestore to write a server-side timestamp. From that documentation link:

// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());

docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
  ...

Upvotes: 2

Related Questions