IO Devs
IO Devs

Reputation: 383

How to save timestamp in Firestore?

I am working on a chat app and I want to store timestamp of my messages. My Data Class for Messages is:

import com.google.firebase.firestore.ServerTimestamp;
import java.util.Date;

public class messgaesDataClass {
    private String messageText;
    private int messageStatus;
    private String messagefrom;
    private @ServerTimestamp Date timestamp;

    public messgaesDataClass(String messageText, int messageStatus, String messagefrom, Date time) {
        this.messageText = messageText;
        this.messageStatus = messageStatus;
        this.messagefrom = messagefrom;
        this.time = time;
    }

    public messgaesDataClass() {
    }

    public String getMessageText() {
        return messageText;
    }

    public void setMessageText(String messageText) {
        this.messageText = messageText;
    }

    public int getMessageStatus() {
        return messageStatus;
    }

    public void setMessageStatus(int messageStatus) {
        this.messageStatus = messageStatus;
    }

    public String getMessagefrom() {
        return messagefrom;
    }

    public void setMessagefrom(String messagefrom) {
        this.messagefrom = messagefrom;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}

I don't understand how to make object of this class. What can I pass in the constructor of this class to initialize timestamp attribute?

Upvotes: 2

Views: 5065

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

To solve this, you should remove the Date time as the argument of your constructor. Your constructor should be like this:

public messgaesDataClass(String messageText, int messageStatus, String messagefrom) {
    this.messageText = messageText;
    this.messageStatus = messageStatus;
    this.messagefrom = messagefrom;
}

There is no need to initialize the time object in your constructor. Firebase servers will read your time field as it is a ServerTimestamp (because of the annotation), and it will populate that filed with the server timestamp accordingly.

Upvotes: 5

Related Questions