为什么我的 Cloud Functions 设置的时间比应该的时间提前一小时?

Why is my Cloud Function setting a time that is one hour ahead of where it should be?

我有一个 Cloud Function 可以重置 Cloud Firestore 上文档字段的日期,但时间戳的小时段设置为午夜。

这会在每天午夜从客户端重置,在客户端触发 Cloud Functions 本身。

但是,Cloud Functions 将日期设置为比预期日期提前一小时。即,如果实际日期是 2022 年 3 月 29 日 00:00:00 UTC+1,则云函数将其设置为 2022 年 3 月 29 日 01:00:00 UTC+1。

我不能使用服务器端时间戳,因为它不允许通过云函数向它添加任何日期,这对于我的用例来说是必需的,因为我有时会重置日期功能的后半部分提前一周。

在昨天更改为 UTC + 1 之前,云功能正常运行并将日期更新为预期的日期和时间(即午夜)。

到目前为止,我将这一天设置为午夜:

 const today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());

然后我通过这个更新文档:

return  ref.doc(doc.id).update({
   "Next Date Due": admin.firestore.Timestamp.fromDate(today)
});

Firestore 时间戳中没有编码时区。它只是使用秒和纳秒(时间戳对象上的字段)的组合来存储与 Unix 纪元的偏移量。

如果您在 Firestore 控制台中查看时间戳字段,您将看到以计算机本地设置使用的本地时区显示的时间。例如,我的系统上有一个本地时区,它是 UTC +8,如果我更新对象字段 "Next Date Due",Firestore 控制台将显示 March 29, 2022 at 8:00:00 AM UTC+8,因为它反映了我系统上的时区,如下面的截图。

您可以尝试在更新后获取时间以仔细检查:

const today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
console.log('today:', today);

ref.doc(doc.id).update({
  "Next Date Due": admin.firestore.Timestamp.fromDate(today)
})
.then(() => {
  ref.doc(doc.id).get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data()["Next Date Due"].toDate());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
  }).catch((error) => {
    console.log("Error getting document:", error);
  });  
});

这将导致:

today: 2022-03-29T00:00:00.000Z
Document data: 2022-03-29T00:00:00.000Z

如果您想为特定时区呈现日期对象,我建议您使用 moment.js.

等库