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

时间:2018-09-09 18:28:02

标签: javascript firebase google-cloud-firestore

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

Firebase Firestore控制台中的屏幕截图:

enter image description here

当我尝试从Firestore返回的对象列表中进行以下操作时:

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

我得到以下输出: enter image description here

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

21 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:10)

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

def feature_4(flower_file='flowers.txt'):

    flower_update = input("Enter the name of the flower you wish to change the price:"
                          "Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
    flower_new_price = input("Enter the updated price of the flower")

    flower, price = [], []
    with open(flower_file) as amend_price:

        for line in amend_price:
            spt = line.strip().split(",")
            flower_price = int(spt[1])
            flower_name = str(spt[0])

            if flower_name == flower_update :
                price.append(flower_new_price)

            else:
                price.append(flower_price)

            flower.append(flower_name)

    with open(flower_file, "w") as f_:
        for i, v in enumerate(flower):
            f_.write("{},{}\n".format(v, str(price[i])))

    print("The new price of", flower_update, "is", flower_new_price)

答案 2 :(得分:10)

您可以将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

答案 3 :(得分:5)

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

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

OutPut示例:Sat 11 Jul 2020 at 21:21:10

答案 4 :(得分:4)

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

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

答案 5 :(得分:3)

最后,我可以得到所需的东西。返回日期为08/04/2020

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

答案 6 :(得分:1)

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

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

答案 7 :(得分:1)

这对我有用。

new Date(firebaseDate.toDate())

答案 8 :(得分:1)

这对我有用

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)

答案 9 :(得分:0)

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

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

答案 10 :(得分:0)

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

答案 11 :(得分:0)

将时间戳存储到 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();

答案 12 :(得分:0)

通常使用任何类型(即 loginDate:any)和 toDate() 在我的所有项目中都没有问题。但在我的上一个项目中它没有。我看到 Timestamp 对象中的 seconds 不再是 _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}}

附言对于此管道,类型并不重要。与 loginDate:any 或 loginDate:Date 配合得很好。

答案 13 :(得分:0)

您可以使用 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)

答案 14 :(得分:0)

其实很简单。使用这个简单的纪元转换器函数将纪元秒转换为 Javascript 日期和时间。

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

timestamp.seconds 传入此函数,然后根据需要将其切片以获取带有日期和时间的文本字符串。

答案 15 :(得分:0)

我以角度工作。

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

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

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

date: firebase.firestore.Timestamp

角管日期工作,但有函数 toDate()

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

答案 16 :(得分:0)

除了其他答案,你也可以这样做

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

答案 17 :(得分:0)

这可能有帮助:

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

答案 18 :(得分:0)

从Firestore获取的时间戳对象具有可以使用的toDate()方法。

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

以下是Firebase文档中有关toDate()方法的引文

将时间戳转换为JavaScript Date对象。这次转换 由于Date对象仅支持毫秒,因此会导致精度下降 精度。

返回Date JavaScript Date对象,该对象代表其中的同一点 时间作为此时间戳记,以毫秒为单位。

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

答案 19 :(得分:0)

我有同样的问题。而且我想像这样:

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

答案 20 :(得分:-1)

一个简单的方法是将 firestore 时间戳转换为纪元时间戳,方法是在 firestore 时间戳上使用 CREATE OR replace PROCEDURE Otc_sp_rpt_ips(par_ruc IN VARCHAR2, par_facturacion IN VARCHAR2, result OUT SYS_REFCURSOR) IS BEGIN IF par_ruc IS NULL THEN BEGIN OPEN RESULT FOR SELECT ca.legal_name "Legal Name/Name", vw.documento_cliente, ph.name "Phone Number", vw.estado_abonado, icc.iccid, icc.imsi, ip.name "IP Address", pi.created_when "Created When" --pi.object_id , pi.name, ca.type FROM r_om_m2m_pi pi join r_ri_private_ip_addr ip ON pi.ip_address = ip.object_id join r_ri_mobile_phone_number ph ON pi.mobile_phone_number = ph.object_id join r_cbm_billing_acct ba ON pi.billing_account = ba.object_id join r_cim_bsns_cust_acct ca ON ba.parent_id = ca.object_id join r_am_sim icc ON pi.sim_card = icc.object_id join otc_t_abonados_mov vw ON ( vw.num_telefonico = ph.name AND estado_abonado <> 'BAA' AND vw.documento_cliente IN ( par_facturacion ) ); END; ELSE BEGIN OPEN RESULT FOR SELECT ca.legal_name AS "Legal Name/Name", vw.documento_cliente, ph.name AS "Phone Number", vw.estado_abonado, icc.iccid, icc.imsi, ip.name AS "IP Address", pi.created_when AS "Created When" --pi.object_id , pi.name, ca.type FROM r_om_m2m_pi pi join r_ri_private_ip_addr ip ON pi.ip_address = ip.object_id join r_ri_mobile_phone_number ph ON pi.mobile_phone_number = ph.object_id join r_cbm_billing_acct ba ON pi.billing_account = ba.object_id join r_cim_bsns_cust_acct ca ON ba.parent_id = ca.object_id join r_am_sim icc ON pi.sim_card = icc.object_id join otc_t_abonados_mov vw ON ( vw.num_telefonico = ph.name AND estado_abonado <> 'BAA' AND vw.account_num IN ( par_ruc ) ); END; END IF; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error In Code'); RETURN; END otc_sp_rpt_ips; 方法。
例如: 您有一个 Firestore 时间戳
toMillis()

created_on : Timestamp { _seconds: 1622885490, _nanoseconds: 374000000 }