【问题标题】:Firebase server-timestamp differs from the correct timeFirebase 服务器时间戳与正确时间不同
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我没有“ServerValue.TIMESTAMP”。我正在使用 FirebaseFirestore,它只有“Timestamp.now()”
  • 编辑:我将 val date: Timestamp = Timestamp.now() 更改为 @ServerTimestamp val date: Timestamp? = null 并成功了。
  • 如果有效,请接受答案
【解决方案2】:

我不确定,但我想我以前见过这种情况,在那种情况下(但我在这里可能错了)我认为运行应用程序的模拟器/手机设置了错误的日期/时间。所以 Timestamp now 也是错误的。

【讨论】:

  • 我已经检查过了。模拟器电话具有正确的时间戳。例如:我发送合约,模拟器时间是13:00,但是timestamp显示的是12:50。
  • 另外,时间戳与手机时间无关,两者相互独立
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 2014-12-12
  • 2020-05-03
相关资源
最近更新 更多