【问题标题】:Date-fns RangeError: Invalid time valueDate-fns RangeError:时间值无效
【发布时间】:2021-08-30 12:16:30
【问题描述】:

您好,我想使用 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

【问题讨论】:

  • 您的feed 变量是以异步方式获取的,对吧?如果你在p 标签上尝试v-if="feed.lengthformatDate(post.timestamp) 会怎样?
  • 您好,我实际上是在为提要使用虚拟数据。存储在字符串中 => 时间戳:'2021-06-12T12:59:57.337Z'

标签: javascript mongodb vue.js timestamp date-fns


【解决方案1】:

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

2021-06-12T12:59:57.337ZSat Jun 12 2021 14:59:57 GMT+0200 (Central European Summer Time) 不同(在我的时区)。
要从一个到另一个,请使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 2020-07-25
    • 2019-06-25
    • 2019-12-23
    • 1970-01-01
    • 2021-06-25
    • 2020-12-31
    • 2017-10-31
    相关资源
    最近更新 更多