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?
Android code
data class MyTimestampPOJO(
val date: Timestamp = Timestamp.now(), // wrong, 15 minutes too early
)
Database screenshot (sending was at 12:50 and not 12:35)
Writing data to firestore
suspend fun sendEmail() {
val data = MyTimestampPOJO()
FirebaseFirestore..getInstance().collection("orders_service").add(data).await()
}
Reading the data
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.)
EDIT ANSWER
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
...
