I am trying to use firebase-server-timestamp to show the user when he/she send their order to us.
The problem I encounter is, that the server-timestamp is showing a wrong time (e.g: Current time is 12:30, but timestamp shows 12:15).
How is that possible?
data class MyTimestampPOJO(
val date: Timestamp = Timestamp.now(), // wrong, 15 minutes too early
)

suspend fun sendEmail() {
val data = MyTimestampPOJO()
FirebaseFirestore..getInstance().collection("orders_service").add(data).await()
}
export const dbOrderServiceOnCreated = functions
.region("europe-west1")
.firestore
.document("orders_service/{id}")
.onCreate((snapshot, context) => {
const data = snapshot.data()
const date = convertTimestampToDate(data.date)
return Promise.resolve()
}
function convertTimestampToDate(stamp: firestore.Timestamp): string {
return new Intl.DateTimeFormat('de-De', { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }).format(stamp.toDate())
}
I am testing this inside the firebase-emulator. The time on my phone is correct (even tho it does not matter, because the server-timestamp is independent to the phone-time, as it should be.)
As both @DIVYANSHU SAHU and @MiniDev99 pointed out, I had several issues. First, instead of using
data class MyTimestampPOJO(val date: Timestamp = Timestamp.now())
one should use
data class MyTimestampPOJO(@ServerTimestamp val date: Timestamp? = null)
The reason for this is, that the second POJO-Timestamp will be populated when the document is written inside the database:
Annotation used to mark a timestamp field to be populated with a server timestamp. If a POJO * being written contains {@code null} for a @ServerTimestamp-annotated field, it will be replaced * with a server-generated timestamp.
Furthermore, every function can have its own region (callable and event-based). Because of this, one should always specify the function region to their specific region (e.g my function region was automatically assigned to us, but I lived in europe).
export const dbOrderServiceOnCreated = functions
.region("europe-west1") // IMPORTANT!!!!
.firestore
...
You can save the Firebase Server time and date rather than the phone's date and time, cuz if you are saving the timestamp of phone it would differ since every phone would have a different time.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);
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