Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the current date/time when I add new value to Firebase Realtime Database

I want to save the current date/time in specific field when I add new value to Firebase Realtime Database via control panel.

How can I achieve that?

Please help me.

like image 598
Leenah Avatar asked Apr 24 '17 09:04

Leenah


People also ask

How is time stored in Firebase?

It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one. It is encoded assuming all minutes are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second table is needed for interpretation.

What is the set () method in Firebase?

Using set() overwrites data at the specified location, including any child nodes.


1 Answers

The best practice is to save your data as a TIMESTAMP like this ServerValue.TIMESTAMP.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);

Also remember, when you set the TIMESTAMP, you set it as a Map, but when you retrieve it, you retrieve it as a Long. To get the data back, i suggest you use this method:

public static String getTimeDate(long timestamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timestamp));
        return dateFormat.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}

Edit: The model class should look like this:

public class YourModelClass {
    //private fields
    private Map<String, String> timestamp;

    public YourModelClass() {}

    //public setters and getters for the fields

    public void setTimestamp(Map<String, String> timeStamp) {this.timestamp= timestamp;}
    public Map<String, String> getTimestamp() {return timestamp;}
}

Remember, ServerValue.TIMESTAMP is just a token that Firebase Realtime Database converts to a number on server side when it's used as a child value during write operation. The date only appears in the database after the write operation completes.

To get the timestamp, there is also another approach, which would be to write a frunction in Cloud Functions for Firebase and it will be as easy as:

exports.currentTime = functions.https.onRequest((req, res) => {
    res.send({"timestamp":new Date().getTime()})
})

You can host this in Cloud Function and get the server timestamp without user interaction.

like image 79
Alex Mamo Avatar answered Sep 19 '22 12:09

Alex Mamo