Firestore Timestamp.fromDate 不是 UTC

Dav*_*sco 1 javascript datetime angular google-cloud-firestore

任何人都知道如何在 Firestore 中保留 UTC 时间戳?

在我的Angular应用程序中,如果我将今天的日期转换为如下所示的时间戳,并且最终UTC+2在 Firestore 数据库中得到一个(现在是瑞士的夏令时)日期

import {firebase} from '@firebase/app';
import '@firebase/firestore';

const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
Run Code Online (Sandbox Code Playgroud)

例如,如果我尝试从冬季时间转换日期,我最终会UTC+1在数据库中使用Timestamp

const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date(2019, 0, 1));
Run Code Online (Sandbox Code Playgroud)

如果我使用,我也会now()得到UTC+2日期

const now: firebase.firestore.Timestamp = firebase.firestore.Timestamp.now();
Run Code Online (Sandbox Code Playgroud)

当我保留数据时,我没有做任何特别的事情:

const now: firebase.firestore.Timestamp = firebase.firestore.Timestamp.now();
const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());

const myData = {
    created_at: now,
    another_value: myTimestamp
};

await this.collection.add(myData);
Run Code Online (Sandbox Code Playgroud)

知道如何UTC为 Firestore创建有效的时间戳吗?

Dou*_*son 10

Firestore 时间戳没有编码到其中的时区。它只是使用秒和纳秒(它们是 Timestamp 对象上的字段)的组合来存储与 Unix 纪元的偏移量。大多数日期/时间对象都是这样的——它们不在乎时区是什么,它只是一个绝对的时间点。

如果您在控制台中查看时间戳字段,您将看到以本地时区显示的时间,您的计算机在其本地设置中使用该时区。

如果将时间戳转换为 JavaScript 日期对象,则该日期对象自然会在浏览器的本地时区中呈现自身,类似于控制台。

如果您想为特定时区呈现 Date 对象,您应该使用一个库来为您执行此操作,例如moment.js

  • 嘿嘿,我也有这个问题。我在 Firestore 控制台中看到日期是 UTC +2,这是我所在的当前 TZ。这意味着 Firestore 只是在我的浏览器中为我格式化 UTC 日期,但它正确地以 UTC 格式存储它?如果是这样,我只丢了3个小时,试图以确保日说UTC + 0。有时我讨厌firestore。 (4认同)
  • 客户端位于哪个时区并不重要。无论您位于世界何处,时间点都是相同的 - 每个人都使用相同的 UNIX 纪元整数偏移量来表示该时间。但是,如果您使用 Date 对象来构造基于小时、分钟和秒的时间点,那么世界各地的人们都会得出不同的值,因为每个 TZ 都有不同的中午 12 点。 (2认同)
  • 一开始我真的发现这很令人困惑,尤其是它是一个数据库,而你期望所见即所得。不管 firestore 的时间戳与时区无关,firestore 控制台不应该只显示实际保存的时间戳而不将其转换为本地时间吗?乍一看,这似乎是一个数据完整性和准确性问题,直到您花费数小时进行调试。为了一些本来应该是微不足道的事情而浪费时间。抱歉,我发现这个实现非常愚蠢。我最近开始讨厌 Google 的一些产品——firestore 和 Go 值得一提:( (2认同)