【问题标题】:Why is moment.js date is 50 years ahead?为什么 moment.js 日期提前 50 年?
【发布时间】:2020-05-26 06:41:33
【问题描述】:

使用 moment 格式化从 firestore 时间戳检索的日期。但是,日期至少相差一天,最多几个月。无论如何,这一年都会减少 50 岁。

这是 Firestore 时间戳

编辑:这是从lastMsg.seconds 记录的内容: 1581372232

我在 FlatList 的 renderItem 中检索以秒为单位的时间:

 renderItem={({ item, index }) => {
        return (
            <Components.InboxItem
                title={item.withName}
                subtitle={item.lastMsg.seconds}
                img={item.withImg}
            />
        );

最后在组件内部我使用 moment 像这样:

const date = moment()
  .utc()
  .startOf('year')
  .seconds(props.subtitle)
  .format('MMMM DD YYYY');

虽然我尝试了多种格式配置,但最接近准确的一种是.startOf("year")。即便如此,日期仍显示为“2070 年 2 月 9 日”。如果.startOf() 更改为“月”、“日”或“小时”,则日期将更改为三月的某个时间。如何解决此问题以在 firestore 中显示日期?

【问题讨论】:

  • 您能否在控制台时间戳的屏幕截图旁边添加您从 firestore 在 js 代码中检索到的实际数据?
  • 编辑时间以秒为单位
  • 问题是 moment().utc().startOf('year') 给你 2020/01/01,而 .seconds(...) 添加等于日期。 unix 纪元 (1970/01/01) 和 2020 年之间的年数为 50,因此您将在 2020 年增加约 50 年。

标签: firebase react-native google-cloud-firestore momentjs


【解决方案1】:

使用moment.unix():

const props = {
  subtitle: 1581372232
};

const date = moment
  .unix(props.subtitle)
  .format('MMMM DD YYYY');

console.log(date);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"&gt;&lt;/script&gt;

因为item.lastMsg.seconds

自 Unix 纪元 1970-01-01T00:00:00Z 以来 UTC 时间的秒数

【讨论】:

  • moment.unix(props.subtitle) 给了我1581375138...然后呢?它不适用于任何其他时刻功能
  • @Jim 我认为.format() 是隐含的。 .unix() 返回一个时刻的实例,而不是一个字符串。
【解决方案2】:

查看https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp,我们既可以获取JS Date 对象,也可以使用toMillis 方法获取毫秒数。

现在这里给出了用于将时间戳转换为时刻对象的简单 moment.js apihttps://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

moment(Number);

现在您可以在 moment 对象上应用格式,如下所示:

moment(Number).format(String);

您的日期错误可能是由于同时使用了utcseconds 而没有将时间戳传递给moment()

【讨论】:

  • 如何在使用 react-native-firebase 读取的 Firestore 中使用 toMillis()?我正在用firebase.firestoreFieldValue.serverTimestamp()lastMsg
  • item.lastMsg 应该是 firestore 时间戳对象,您可以在其上调用该函数。我认为 react-native-firebase 库也应该这样做。
  • 啊最初当我尝试doc.get('time').toMillis() 时它没有工作。第二次尝试它的工作原理
猜你喜欢
  • 2022-01-11
  • 2022-11-21
  • 1970-01-01
  • 2012-01-31
  • 2019-09-09
  • 2016-08-22
  • 2019-03-31
  • 2016-05-07
  • 1970-01-01
相关资源
最近更新 更多