繁体   English   中英

如何将 Firestore 日期/时间戳转换为 JS Date()?

[英]How do I convert a Firestore date/Timestamp to a JS Date()?

我正在尝试将以下日期转换为 javascript Date() object。当我从服务器取回它时,它是一个时间戳 object,

来自 Firebase Firestore 控制台的截图:

在此处输入图像描述

当我在从 firestore 返回的对象列表上尝试以下操作时:

  list.forEach(a => {
    var d = a.record.dateCreated;
    console.log(d, new Date(d), Date(d))
  })

我得到这个 output: 在此处输入图像描述

显然,时间戳都是不同的,并且并非都是 2018 年 9 月 9 日(恰好是今天)的同一日期。 我也不确定为什么new Date(Timestamp) results in an invalid date 我是一个 JS 新手,我在日期或时间戳方面做错了吗?

JavaScript Date 的构造函数对 Firestore Timestamp对象一无所知——它不知道如何处理它们。

如果要将时间戳转换为日期,请在时间戳上使用toDate()方法。

您可以使用 toDate() 函数和 toDateString() 单独显示日期部分。

const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017

假设您只想要时间部分,然后使用 toLocaleTimeString()

const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional

您可以使用Timestamp.fromDate.toDate来回转换。

// Date to Timestamp
const t = firebase.firestore.Timestamp.fromDate(new Date());

// Timestamp to Date
const d = t.toDate();

请使用toDate()方法,然后使用像这样的角管将其转换为格式 -

   {{ row.orderDate.toDate() | date: 'dd MMM hh:mm' }}

如何将 Unix 时间戳转换为 JavaScript Date 对象。

var myDate = a.record.dateCreated;
new Date(myDate._seconds * 1000); // access the '_seconds' attribute within the timestamp object

除了其他答案之外,您也可以这样做

 //date from firebase is represented as let time = { seconds: 1613748319, nanoseconds: 47688698687, } const fireBaseTime = new Date( time.seconds * 1000 + time.nanoseconds / 1000000, ); const date = fireBaseTime.toDateString(); const atTime = fireBaseTime.toLocaleTimeString(); console.log(date, atTime);

const timeStampDate = record.createdAt;
const dateInMillis  = timeStampDate._seconds * 1000

var date = new Date(dateInMillis).toDateString() + ' at ' + new Date(dateInMillis).toLocaleTimeString()

输出示例: Sat 11 Jul 2020 at 21:21:10

终于,我可以得到我需要的东西了。 这将返回日期为08/04/2020

new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()

这可能会有所帮助:

new Date(firebaseDate._seconds * 1000).toUTCString()

您从 firestore 获得的时间戳对象有一个可以使用的toDate()方法。

list.forEach(a => {
  var d = a.record.dateCreated;
  console.log(d.toDate())
})

这是 firebase 文档中关于toDate()方法的引用

将 Timestamp 转换为 JavaScript Date 对象。 此转换会导致精度损失,因为 Date 对象仅支持毫秒精度。

返回 Date JavaScript Date 对象,表示与此时间戳相同的时间点,精度为毫秒。

https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#todate

一种简单的方法是将 firestore 时间戳转换为 epoch 时间戳,方法是在 firestore 时间戳上使用toMillis()方法。
例如:您有一个 Firestore 时间戳
created_on : Timestamp { _seconds: 1622885490, _nanoseconds: 374000000 }

let epochTimestamp = created_on.toMillis()
//epochTimestamp = 1621081015081
//Now this timestamp can be used as usual javascript timestamp which is easy to manipulate.
let date = new Date(epochTimestamp) //date = Sat May 15 2021 17:46:55 GMT+0530 (India Standard Time)

这对我有用。

new Date(firebaseDate.toDate())

这对我有用

let val = firebase.timestamp // as received from the database, the timestamp always comes in an object similar to this - {_nanoseconds: 488484, _seconds: 1635367}
    (new Date( (val.time._seconds + val.time._nanoseconds * 10 ** -9) * 1000)).toString().substring(17, 21)

这里有很多答案,但作为一个菜鸟,我发现他们中的大多数都令人困惑。

所以对于像我这样的新手来说,这里简单解释一下如何将 Firestore 日期/时间戳转换为 Javascript Date() 以及为什么需要这样做。

为什么要转换?

Firestore 将日期存储为时间戳对象 这与 Javascript Date() 对象不同。

这让我很困惑,因为如果您将 Date() 对象发送到 Firestore,然后检索它,它会将您返回一个 Timestamp 对象。 就像你给 Firestore 一美元,它会给你 4 个季度。 这是相同数量的钱(或相同的日期),但如果你期待的是纸,并且得到了金属,你会感到困惑。

如何转换

幸运的是 Timestamp 对象有内置的函数给你一个 Javascript Date 对象: toDate

注意:请记住, toDate看起来像 Javascript toLocaleDateString()toDateString()但它不是。 JS Date() 对象和 Firestore Timestamp 对象是不一样的,所以不要让我的菜鸟错误尝试使用其中一个函数,另一个。

要将 Firestore 时间戳转换为 Javascript 日期,只需在时间戳上调用.toDate()

//get the document from Firestore
let fireStoreTimestamp = doc.data().nameOfYourDateField;
let javascriptDate = fireStoreTimestamp.toDate();

我有同样的问题。 我发现是这样的:

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

// then using dayjs library you can display your date as you want.

const formatDate = dayjs.unix(createdAt.seconds).format('YYYY-MM-DD');

输出应该看起来像例如2020-08-04

如果您不想丢失毫秒,您可以执行以下操作:

var myDate = a.record.dateCreated;
new Date((myDate.seconds + myDate.nanoseconds * 10 ** -9) * 1000);

我在角度工作。

我有一个界面和一个字段日期:日期。

角管日期无效:order.date | 日期:'中'

我在界面中更改字段日期的类型

date: firebase.firestore.Timestamp

角管道日期工作,但功能 toDate()

order.date.toDate() | date:'medium'

真的很简单。 使用这个简单的纪元转换器功能,将纪元秒数转换为 Javascript 日期和时间。

  function getUNIXTime(dt) {
    let unix = new Date(dt * 1000);
    return unix.toUTCString().slice(5, 16);   
}

timestamp.seconds传递给此函数,然后根据您的需要对其进行切片,以获得带有日期和时间的文本字符串。

您可以使用dayjs库将 Firebase Firestore 时间戳秒转换为您的本地时间。

newDate =  dayjs.unix(date.seconds).$d;

这将需要

date: { 
    seconds: 1639506600, 
    nanoseconds: 0 
}

并将其转换为

Date Sat Nov 16 2019 00:00:00 GMT+0530 (India Standard Time)

通常使用任何类型(即 loginDate:any)和 toDate() 在我的所有项目中都没有问题。 但在我的上一个项目中没有。 我看到 Timestamp 对象中的秒数不再是_seconds (Firebase 8.6.8)。 这种类型的变化可能已经影响了它。 我不知道,但我没有时间,所以我使用了替代解决方案。 自定义管道。 它可以用作替代方案:

import { Pipe, PipeTransform } from '@angular/core';
import { formatDate } from '@angular/common';

@Pipe({
  name: 'timestamp'
})
export class TimestampPipe implements PipeTransform {

  transform(value: any, format?: string) {

    if (!value) { return ''; }
    if (!format) { format = 'dd MMM  yy'; }

    return formatDate(value._seconds * 1000, format, 'tr');
  }
}

{{ item.endDate | timestamp}}

PS 类型对于此管道并不重要。 使用 loginDate:any 或 loginDate:Date 很好。

将时间戳存储到 Firestore 中:

import * as firebaseAdmin from "firebase-admin";

const created = firebaseAdmin.firestore.FieldValue.serverTimestamp();

// type
created: FirebaseFirestore.Timestamp | FirebaseFirestore.FieldValue | undefined;

js Date对象的形式回读

const createDate = (created as FirebaseFirestore.Timestamp).toDate();

作为RFC3339字符串回读

const createDate = (created as FirebaseFirestore.Timestamp).toDate().toISOString();

Web Firestore 时间戳:

function dateToFirestoreTimestamp(dateString = ''){
        var timestampDate = new Date();     // this will return current date-time
        if(dateString != ''){
            // this will return timestamp according to provided date-time
            dateString = dateString.replace(' ', 'T');
            timestampDate = new Date(dateString);
        } 
        timestampDate = firebase.firestore.Timestamp.fromDate(timestampDate);
        return timestampDate;
    }

这是迄今为止将firebase时间戳转换为日期的最优雅,最精确和最简单的方法(不需要依赖等)

const date = new Intl.DateTimeFormat(
    'de-De', { 
           year: 'numeric', 
           month: 'numeric', 
           day: 'numeric', 
           hour: 'numeric', 
           minute: 'numeric' 
    }
).format(firebaseTimeStamp.toDate())

这是一个包含所有必要参数的备忘单

这是firestore timestampJavascript Date() object之间的不同之处。 如果你想使用 firestore 时间戳中的 javascript Date() 对象,这就是我所做的:

const foo = new Date(firestoreTimestamp.toDate());

然后你可以像往常一样使用javascript Date() 对象。 这里有一些参考:

https://www.w3schools.com/jsref/jsref_obj_date.asp

例如,我们想从 Date() 对象中以字符串格式检索日期:

const foo = new Date(firestoreTimestamp.toDate());
foo.toLocaleDateString();

等等

为了帮助那些仍在寻找将 Firestore 日期转换为 JS 日期以在 Web 应用程序中显示的答案的人。 这是一个使用打字稿的例子......

import {
  Timestamp,
} from "firebase/firestore";

interface IStuff {
  createdAt: Timestamp;
}

const insertStuff = async (text: string) => {
    await addDoc(collection(db, "coolstuff"), {
      text,
      createdAt: serverTimestamp(),
    });
};

<p>{item.createdAt?.toDate().toDateString()}</p>

// OR

<p>{item.createdAt?.toDate().toLocaleTimeString()}</p>

扩展 Waleed Tariq 答案,以获得更具可读性的字符串:

 function formatDate(date) { const formatDate = new Date( date.seconds * 1000 + date.nanoseconds / 1000000 ); return formatDate.toLocaleTimeString('en-us', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); } const timeStamp = {nanoseconds: 184000000, seconds: 1664826910}; console.log(formatDate(timeStamp))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM