javascript - 日期-fns RangeError : Invalid time value

标签 javascript mongodb vue.js timestamp date-fns

您好,我想使用 date-fns 将 mongo db created_at 时间戳转换为它说 ... 分钟/小时前的时间图书馆。该函数称为 formatDistanceToNow,它返回自提供的日期时间以来的时间。我在前端使用 Vue,但似乎无法正常工作。

<template>
    <div class="feed">
      <div v-for="post in feed" :key="post.id" class="post">
        <h3>{{ post.name }}</h3>
        <p>{{ post.timestamp }}</p> // return 2021-06-12T12:59:57.337Z
        <p>{{ Date(post.timestamp) }}</p> // return Mon Jun 14 2021 16:02:22 GMT+0100 (British Summer Time)
        <!-- <p>{{ formatDate(post.timestamp) }}</p> -->
        <!-- <p>{{ formatDate(Date(post.timestamp)) }}</p> -->
      </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { formatDistanceToNow } from 'date-fns'

export default {
  computed: {
    ...mapState(['feed']),
    formatDate(timestamp){
      return formatDistanceToNow(timestamp)
    }
  }
}
</script>

2行注释的代码是我试过的,但不断出现以下错误

Uncaught (in promise) RangeError: Invalid time value

最佳答案

您不能将参数传递给计算函数,所以在这里您需要使用方法。此外,时间格式确实不正确,如文档页面所示:https://date-fns.org/v2.22.1/docs/formatDistanceToNow

2021-06-12T12:59:57.337ZSat Jun 12 2021 14:59:57 GMT+0200(中欧夏令时) 不同(在我的时区)。
要从一个转到另一个,请使用 new Date("2021-06-12T12:59:57.337Z")

最终代码看起来像这样

<template>
  <div>
    format: {{ formatDate(test) }}
  </div>
</template>

<script>
export default {
  data() {
    test: '2021-06-12T12:59:57.337Z',
  },
  methods: {
    formatDate(timestamp) {
      return formatDistanceToNow(new Date(timestamp))
    },
  }
}
</script>

关于javascript - 日期-fns RangeError : Invalid time value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67972820/

相关文章:

nginx - Axios 中的 Cors OPTIONS 方法在 Laravel 和 Nginx 中失败

javascript - 使用 element ui vue js 固定侧组件

javascript - 错误: Object doesn't support property or method 'moment'

mongodb - Mongodb 中的 Scons

node.js - MongoDB CursorNotFound 在 collection.find() 上出现数百个小记录错误

node.js - 使用 Mongoose 使用 arrayFilters 查找

javascript - 饼图在每次刷新时都会在某些显示器上调整大小

javascript - 从 JavaScript 中的字符串中删除 FILL

javascript - ionic 查找是否通过 parent 点击事件点击了 child

javascript - socket.on 不在客户端工作