Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda