Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
I can't convert my datetime into mins, seconds and etc

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`
    }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can calculate 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`;
};
about 4 years ago · Juan Pablo Isaza Report

0

From moment.js docs

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

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!