【发布时间】:2022-01-03 16:51:17
【问题描述】:
我正在尝试使用firebase-server-timestamp 在用户向我们发送订单时显示。
我遇到的问题是,server-timestamp 显示的时间错误(例如:当前时间是 12:30,但时间戳显示 12:15)。
这怎么可能?
安卓代码
data class MyTimestampPOJO(
val date: Timestamp = Timestamp.now(), // wrong, 15 minutes too early
)
数据库截图(发送时间是 12:50 而不是 12:35)
将数据写入 Firestore
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())
}
我正在firebase-emulator 中对此进行测试。我手机上的时间是正确的(尽管这并不重要,因为server-timestamp 应该独立于手机时间。)
编辑答案
正如@DIVYANSHU SAHU 和@MiniDev99 指出的那样,我遇到了几个问题。首先,而不是使用
data class MyTimestampPOJO(val date: Timestamp = Timestamp.now())
应该使用
data class MyTimestampPOJO(@ServerTimestamp val date: Timestamp? = null)
这样做的原因是,当文档写入数据库时,第二个 POJO-Timestamp 将被填充:
用于标记要填充时间戳字段的注释 服务器时间戳。如果正在写入的 POJO * 包含 {@code null} for @ServerTimestamp-annotated 字段,它将被 * 替换为 服务器生成的时间戳。
此外,每个函数都可以有自己的区域(可调用和基于事件)。因此,应该始终将功能区域指定给他们的特定区域(例如,我的功能区域是自动分配给我们的,但我住在欧洲)。
export const dbOrderServiceOnCreated = functions
.region("europe-west1") // IMPORTANT!!!!
.firestore
...
【问题讨论】:
-
您在哪里,欧洲、美国、亚洲?
-
@AlexMamo Europe
-
请编辑您的问题并展示您将数据写入 Firestore 的方式。
-
@AlexMamo 已编辑
-
我想我知道发生了什么,你的服务器在另一个时区,你的手机在另一个时区,所以当服务器时间是 12:00 时,你的时间是它之前/之后的 15 分钟根据您的时区。所以你只需要根据前端时区相应地增加或减少时间。
https://stackoverflow.com/a/66079801/13139719这个回答讲了这个问题。
标签: android firebase google-cloud-firestore google-cloud-functions timestamp