I’m building social media app using next.js. I want to display relative time in my project.
next.js
Expected output :
just now 2 minutes ago 1 hour ago 2 days
I want to retrieve time from MongoDB document
MongoDB
Tried to use moment and dayjs, but i’m facing some trouble in getting started. Can anyone help me?
moment
dayjs
2
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.
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`
Click here to cancel reply.
2
Answers
You can use react-timeago:
This will generate the auto-generated text that looks like:
They also support custom formatting options.
You need not use any external npm package to do this.
You can get the time difference here.
And