如何使用dayjs相对时间

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

大家好,我在使用 Dayjs 相对时间时遇到了这个奇怪的问题

之前我使用momentjs

var date = "2021-02-26 16:04:15";
moment(date).fromNow();

相对时间总会按预期增加

20 minutes ago, then increase to 21 minutes ago, then increase to 22 minutes ago

但是当我使用dayjs时,相对时间并没有增加。它适用于页面加载,但不会增加

import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

var date = "2021-02-26 16:04:15";
dayjs(date).fromNow();

输出

20 minutes ago, and never increase. Just static

是否有我错过的配置或者dayjs没有提供相对时间的自动更新?

momentjs dayjs
1个回答
0
投票

经过我的研究,我认为 Day Js 与 MomentJS 相比没有自动递增相对时间

所以我只需要使用 setTimeout 每 60 秒自动发出一次包含最新时间戳的事件。

所有需要相对时间的地方都会被通知更新状态

Vue JS 中的示例

app.js

created() {

    let self = this;

    this.timer = setInterval(function () { self.$eventBus.$emit("updateTimeLabel", new Date()); }, 60000);

},
beforeDestroy() {
    clearInterval(this.timer)
}

时间标签.vue

props: {
    timestamp: {
      type: String,
      required: true,
    },
},
data() {
    return {
      from_now: null,
    };
},
created() {
    this.from_now = this.$fromNow(this.timestamp);

    // every one minute, app.js will emit event to update all TimeLabel.vue relative time

    this.$eventBus.$on("updateTimeLabel", (datetime) => {
      this.from_now = this.$fromNow(this.timestamp);
    });
},
methods: {

    $fromNow(timestamp) {
      return dayjs.utc(timestamp.substring(0, 23)).local().fromNow();
    },
}
© www.soinside.com 2019 - 2024. All rights reserved.