Firestore Timestamp.fromDate 不是 UTC [英] Firestore Timestamp.fromDate not UTC

查看:15
本文介绍了Firestore Timestamp.fromDate 不是 UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何在 Firestore 中保留 UTC 时间戳吗?

Anyone knows how to persist UTC Timestamp in Firestore?

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

In my Angular app, if I convert today's date to a Timestamp like the following and I end up with a UTC+2 (it's summer time here right now in Switzerland) date in the Firestore database

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

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

例如,如果我尝试从冬季时间转换日期,我最终会得到 UTC+1 数据库中的时间戳

If for example I try to convert a date from the winter time, I end up with UTC+1 Timestamp in the database

const myTimestamp = firebase.firestore.Timestamp.fromDate(new Date(2019, 0, 1));

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

If I would use now() I end up with UTC+2 dates too

const now: firebase.firestore.Timestamp = firebase.firestore.Timestamp.now();

我在保存数据时没有做任何特别的事情:

I don't do anything particular when I persist the data:

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);

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

Any idea how is it possible to create valid UTC Timestamp for Firestore?

推荐答案

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

Firestore timestamps don't have a timezone encoded into them. It just stores the offset from the Unix epoch using a combination of seconds and nanoseconds (which are fields on the Timestamp object). Most date/time objects are like this - they don't care what the timezome is, it's just an absolute point in time.

如果您在控制台中查看时间戳字段,您将在本地设置中看到以本地时区显示的时间.

If you view a timestamp field in the console, you will see the time displayed in the local timezone that your computer uses from its local settings.

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

If you convert a timestamp to a JavaScript Date object, that date object naturally renders itself in the browser's local timezome, similar to the console.

如果你想为一个特定的时区渲染一个 Date 对象,你应该使用一个库来为你做,比如 moment.js.

If you want to render a Date object for a specific timezone, you should use a library to do that for you, such as moment.js.

这篇关于Firestore Timestamp.fromDate 不是 UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆