Search code examples
node.jsmongodbexpressdayjs

Display dayjs time from when post was created


So I have an express app where you can make posts and such. I want to display how long ago the post was made ie. 5 minutes ago. I have been looking at day.js docs and they say to use:

    dayjs(date).fromNow();

The problem with this is that it is displaying the time from right now. How can I display the time from when the post was created.

Btw date is stored in my mongodb database.


Solution

  • You need to extend dayjs with relativeTime. Sample code provided below. Refer link

    const dayjs = require("dayjs");
    const relativeTime = require("dayjs/plugin/relativeTime");
    dayjs.extend(relativeTime);
    
    let dateNow = dayjs();
    let blogDate = "2020-01-01";
    let str = dateNow.from(blogDate, true);
    console.log(str); // 9 months