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

156
Visualizações
Date-fns format distance is not in correct words

I am facing a problem with the UI and want to show the timestamp distance into 3 hours ago and 4 hours ago etc. The timestamp coming from the server with a property named createdAt which has the following value.

createdAt: "2021-10-27T05:24:37.642Z"

To solve this problem I am using library like date-fns v2.25.0 builtin function formatDistance.

import { formatDistance} from 'date-fns';

const timestamp = createdAt ? new Date(createdAt) : '';
console.log(formatDistance(Date.now(), timestamp, {addSuffix: true}));
    

But it is giving back the distance in the following words

in about 3 hours
in about 4 hours

instead of

3 hours ago
4 hours ago

What I am doing wrong? If you know any other good library please you can share.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use any other popular package such as moment, which I do believe have more custom configuration, but if you want to use this package, instead of having to change the formatDistance function, it would be easier to change the result string like:

import { formatDistance } from "date-fns";

const createdAt = "2020-08-27T08:24:37.642Z";
const timestamp = createdAt ? new Date(createdAt) : "";
const distance = formatDistance(Date.now(), timestamp, {addSuffix: true });

console.log(distance.substring(distance.indexOf(distance.match(/\d+/g))));

// => 2 hours ago
about 4 years ago · Juan Pablo Isaza Relatório

0

Reverse the arguments:

console.log(formatDistance(timestamp, Date.now(), {addSuffix: true}));
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