'How to use dayjs relative time

Hi guys I have this weird problem when using Dayjs relative time

Previously I use momentjs

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

The relative time will always increase as expected

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

However when I use dayjs, the relative time is not increase. It works on page load, but never increase

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

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

Output

20 minutes ago, and never increase. Just static

Is there any configuration that I miss or dayjs doesnt provide auto update on relative time?



Solution 1:[1]

After my research, I believe Day Js does not have auto increment relative time, as compare to MomentJS

So I just need to use setTimeout to auto emit event every 60 seconds contains the latest timestamp.

And all place that need relative time will be notify to update the state

Example in Vue JS

app.js

created() {

    let self = this;

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

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

TimeLabel.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();
    },
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cyberfly