skip to Main Content

I’m building social media app using next.js. I want to display relative time in my project.

Expected output :

just now
2 minutes ago
1 hour ago
2 days

I want to retrieve time from MongoDB documentdocument

Tried to use moment and dayjs, but i’m facing some trouble in getting started. Can anyone help me?

2

Answers


  1. You can use react-timeago:

    import TimeAgo from 'react-timeago';
    
    ...
    <TimeAgo date={date} />
    

    This will generate the auto-generated text that looks like:

    2 minutes ago
    3 days ago
    4 months ago
    1 year ago
    

    They also support custom formatting options.

    Login or Signup to reply.
  2. You need not use any external npm package to do this.

    export const getTimeDifference = (targetDate: string) => {
      const difference = new Date().getTime() - new Date(targetDate).getTime()
    
      if (difference > 0) {
        const timeLeft = {
          days: Math.floor(difference / (1000 * 60 * 60 * 24)),
          hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
          minutes: Math.floor((difference / 1000 / 60) % 60),
          seconds: Math.floor((difference / 1000) % 60),
        }
        return timeLeft
      }
    
      return undefined
    }
    

    You can get the time difference here.

    And

    const timeDiff = getTimeDifference(your Mongodb time string)
    const timeString = `${timeDiff.days} days ${timeDiff.hours} hours ${timeDiff.minutes} minutes ${timeDiff.seconds} seconds`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search