Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
date should be format automatically according to time in javascript

I have a date string like "2022-05-19T14:44:18.887Z". I am creating a blog website in react so, I just want to show the time how old the post is. so i want to show the time like for example 2 min ago, 2 hrs ago, 10 hrs ago , 1 day ago, 5 days ago then 6 days ago. when As soon as the post becomes 7 days old then it should show the month and year of that post like, May 22. It all the things should be automatically. For this i have used moment library. But i am unable to implement it. Please anyone can help me on this.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Please try this stuff

import moment from 'moment';

export const _convertTimeHumanReadable = (date) => {
  if (!date) return '';
  const segs = date.split(' ');
  if (segs.length > 1) {
      date = segs[0] + 'T' + segs[1];
  }
  const data = moment(date);
  const now = moment();
  let result = '';
  if (data.format('YYYY') !== now.format('YYYY')) {
      result = result + data.format('YYYY');
  }
  result = result + data.format('M/DD');
  return result;
};

export const convertTimeHumanReadable = (date) => {
  if (!date) return '';
  const now = moment();
  const data = moment(date);
  const duration = moment.duration(data.diff(now))
  if (duration.days() < -1) {
    return _convertTimeHumanReadable(date);
  }
  return duration.humanize(true);
}

This code humanize the date format up to 1 day ago and if you can change -1 to -7 then humanize up to 7 days ago

  if (duration.days() < -1) {
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda