gpt4 book ai didi

android - Firebase 服务器时间戳与正确时间不同

转载 作者:行者123 更新时间:2023-12-04 23:55:44 25 4
gpt4 key购买 nike

我正在尝试使用 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)

enter image description here

将数据写入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 将被填充:

Annotation used to mark a timestamp field to be populated with aserver timestamp. If a POJO * being written contains {@code null} fora @ServerTimestamp-annotated field, it will be replaced * with aserver-generated timestamp.

此外,每个函数都可以有自己的区域(可调用和基于事件)。因此,应该始终将功能区域指定到他们的特定区域(例如,我的功能区域是自动分配给我们的,但我住在欧洲)。

export const dbOrderServiceOnCreated = functions
.region("europe-west1") // IMPORTANT!!!!
.firestore
...

最佳答案

您可以保存 Firebase 服务器时间和日期而不是手机的日期和时间,因为如果您要保存手机的时间戳,它会有所不同,因为每部手机都有不同的时间。

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

关于android - Firebase 服务器时间戳与正确时间不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70110641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com