如何解决Date-fns RangeError:无效的时间值
嗨,我想使用 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>
未捕获(承诺)RangeError:时间值无效
解决方法
您不能将参数传递给计算函数,因此在这里您需要使用 method
。此外,时间格式确实不好,如文档页面所示:https://date-fns.org/v2.22.1/docs/formatDistanceToNow
2021-06-12T12:59:57.337Z
与 Sat 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。