Currently, the Google's version of ServerValue.TIMESTAMP
returns {".sv":"timestamp"}
which is used as a directive for Firebase to fill that field with the server timestamp once you save the data to the Firebase server.
When you create your data on the client side however, you don't have the actual timestamp to play with yet (ie. use as the creation date). You only will have an access to the timestamp after the initial save and consequent retrieval, which - I imagine - is sometimes too late and not very elegant.
Before Google:
Update: Ignore this section as it is incorrect - I misunderstood the examples. ServerValue.TIMESTAMP
always returned the {".sv":"timestamp"}
.
As far as I understand in pre-google Firebase there seemed to be a server-generated timestamp available that allowed you to acquire the actual timestamp:
import com.firebase.client.ServerValue;
ServerValue.TIMESTAMP // eg. 1466094046
(ref 1, ref 2)
Questions:
Note:
I'm not considering using new Date()
on client side as I've been reading it's not safe, though please share your thoughts if you think different.
To convert a Firestore date or timestamp to a JavaScript Date, we use firebase. firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp.
firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.
To reach the timestamp of firebase server on client, you first need to write the value to the server then read the value. firebase. database(). ref('currentTime/').
As of SDK Version 7.10. 0, you can directly compare Timestamp objects with the JavaScript arithmetic inequality comparison operators ( < , <= , > , and >= ). To check if two Timestamp objects are temporally identical you must use the isEqual property (docs).
When you use the ServerValue.TIMESTAMP
constant in a write operation, you're saying that the Firebase Database server should determine the correct timestamp when it executes the write operation.
Let's say we run this code:
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
}
public void onCancelled(DatabaseError databaseError) { }
});
ref.setValue(ServerValue.TIMESTAMP);
This will execute as follows:
ServerValue.TIMESTAMP
If you're using ChildEventListener
instead of a ValueEventListener
, then the client will call onChildAdded
in step 3 and onChildChanged
in step 8.
Nothing changed in the way we generate the ServerValue.TIMESTAMP
since Firebase joined Google. Code that worked before, will continue to work. That also means that the first answer you linked is a valid way to handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With