Home > front end >  I can't convert my datetime into mins, seconds and etc
I can't convert my datetime into mins, seconds and etc

Time:03-16

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`
    }
}

CodePudding user response:

From moment.js docs

moment(date).fromNow();     // 4 years ago
moment(date).fromNow(true);     // 4 years

https://momentjs.com/docs/#/displaying/fromnow/

CodePudding user response:

You can calculare the seconds ago by comparing to the current date as in the example below.
Working Stackblitz demo

As of today, moment is no longer needed, and you can use pure javascript to convert a string to date object. Source : Momentjs documentation or check this article

Moment was built for the previous era of the JavaScript ecosystem. The modern web looks much different these days.

const convertDate = (date: string) => {
  let current_date = new Date().getTime();

  let d = (current_date - new Date(date).getTime()) / 1000;

  let min = Math.round(d / 60);
  if (min <= 60) {
    return `${min} min(s) ago`;
  }

  let hours = Math.round(d / 3600);
  if (hours <= 60) {
    return `${hours} hour(s) ago`;
  }

  let day = Math.round(d / 86400);
  if (day <= 30) {
    return `${day} day(s) ago`;
  }

  let month = Math.round(day / 30);
  if (month <= 30) {
    return `${month} month(s) ago`;
  }

  let year = Math.round(month / 12);
  if (year <= 365) {
    return `${year} year(s) ago`;
  }

  return `${d} second(s) ago`;
};
  • Related