React-显示Firestore时间戳记

问题描述 投票:0回答:2

我试图弄清楚如何在React应用中显示Firestore时间戳。

我有一个Firestore文档,其中的字段名为createdAt。

我正在尝试将其包含在输出列表中(此处提取相关位,以便您不必通读整个字段列表)。

componentDidMount() {
    this.setState({ loading: true });

    this.unsubscribe = this.props.firebase
      .users()
      .onSnapshot(snapshot => {
        let users = [];

        snapshot.forEach(doc =>
          users.push({ ...doc.data(), uid: doc.id }),
        );

        this.setState({
          users,
          loading: false,
        });
      });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { users, loading } = this.state;

    return (
        <div>
    {loading && <div>Loading ...</div>}

            {users.map(user => (

                <Paragraph key={user.uid}>  

       <key={user.uid}>  
       {user.email}
       {user.name}
       {user.createdAt.toDate()}
       {user.createdAt.toDate}
       {user.createdAt.toDate()).toDateString()}

唯一不显示的属性是日期。

以上每次尝试都会产生一个错误,指出:

TypeError:无法读取未定义的属性'toDate'

我见过this postthis postthis postthis post和其他类似的对象,这表明toDate()应该起作用。但是-此扩展名对我抛出错误-包括当我尝试toString扩展名时。

[我知道它知道Firestore中有什么东西,因为当我尝试user.createdAt时,我收到一条错误消息,指出它找到了一个包含秒数的对象。

enter image description here

javascript reactjs firebase google-cloud-firestore unix-timestamp
2个回答
0
投票

因此,firestore将日期存储为具有秒和纳秒的对象。如果需要创建用户的时间,则可以引用user.createdAt.nanoseconds。这将返回unix时间戳。

您想如何在应用程序中显示日期?如果要获取日期对象,则可以将时间戳传递到new Date(user.createdAt.nanoseconds)这样的日期构造函数中。我个人喜欢使用date-fns库来处理时间。


0
投票

当您从Firestore获取时间戳时,它们属于以下类型:

enter image description here

要将其转换为正常时间戳,可以使用.toDate()函数。

例如,对于如下文档:

enter image description here

我们可以使用类似:

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  console.log(doc.data().[FIELD].toDate());
});

输出将类似于:

2019-12-16T16:27:33.031Z

现在可以进一步处理该时间戳,您可以将其转换为字符串,并根据需要使用regex对其进行修改。

例如:((我在这里使用Node.js)

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  var stringified = doc.data().[FIELD].toDate().toISOString();
  //console.log(stringified);
  var split1 = stringified.split('T');
  var date = split1[0].replace(/\-/g, ' ');
  console.log(date);
  var time = split1[1].split('.');
  console.log(time[0]);
});

将给您这样的输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.