Table of Contents
Issue
I’m giving 2022-03-12T22:57:20.734546Z
as the date argument. I give the datetime as input and then check using conditions and returning foo seconds ago
or foo mins ago
etc but I’m getting output as 20 seconds ago
and its not updating.
const convertDate = (date: string) => {
let d = moment(date).seconds();
let min = d / 60;
let hours = d / 3600
let day = d / 86400
let month = day / 30
let year = month / 12
if (min <= 60) {
return `${min} min(s) ago`
} else if (hours <= 60) {
return `${hours} hour(s) ago`
} else if (day <= 30) {
return `${day} day(s) ago`
} else if (month <= 30) {
return `${month} month(s) ago`
} else if (year <= 365 ) {
return `${year} year(s) ago`
} else {
return `${d} second(s) ago`
}
}
Solution
From moment.js docs
moment(date).fromNow(); // 4 years ago
moment(date).fromNow(true); // 4 years
https://momentjs.com/docs/#/displaying/fromnow/
Answered By – Shahriar Shojib
Answer Checked By – Timothy Miller (BugsFixing Admin)