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

219
Visualizações
React: Converting mongoDB date to human readable date

A document stored in MongoDB has a "createdAt" property, which contains a timestamp. Here we have an example of the timestamp:

createdAt: 2021-10-26T12:24:33.433+00:00

Considering this date is today, how can I reproduce the following behavior?:

  • Display this date as "Today at 12:24 PM"
  • Tomorrow, display this date as "Yesterday at 12:24 PM"
  • From the day after tomorrow and beyond, display it as "26/10/2021 at 12:24 PM"

I tried using the JavaScript's Date instance to compare both strings but I got into some trouble trying to convert the strings properly. I was wondering if there's any library that could ease the process or some conventional way to do it.

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

0

Since you mention using React, I assume that you have a Node running there somewhere. Maybe a create-react-app backend? I will also assume ESM.

You would achieve something like this with date-fns; see docs at https://date-fns.org/v2.25.0/docs/formatDistance

$ npm i date-fns First, install dependency, then test it like below:

import formatDistance from 'date-fns/formatDistance'

function TestComponent() {
   const dateStr = "2021-10-26T12:24:33.433+00:00";
   const str = formatDistance(
       new Date(dateStr),
       new Date()
   );
   return <h1>{str}</h1>
}
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