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

214
Visualizações
Format time in JS

So I'm making a userinfo command

I use moment.js for relative time

moment(timestamp).fromNow() \\ 2 years ago

Is there a way to format it like 2 years x days, x seconds ago etc

enter image description here

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

0

I don't think there's an easy way to do this with Moment.js.

However, using Luxon (successor to Moment.js) you can create an interval, convert it to a duration then format the values. E.g. to get the years, months and days from the ECMAScript epoch to now:

// Create an interval from 1 Jan 1970 UTC to now
let interval = luxon.Interval.fromDateTimes(
  new Date(0), // 1 Jan 1970 UTC
  new Date()   // now
);

// Show default interval object
console.log(interval.toFormat('yyyy-MM-dd'));

// Convert to duration object
let d = interval.toDuration(['years','months','days']).toObject();

// Display in friendly format
let text = [];
d.years? text.push(d.years + ' years') : null;
d.months? text.push(d.months + ' months') : null;
d.days? text.push(d.days.toFixed(1) + ' days') : null;

console.log(text.join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.0/luxon.min.js"></script>

Note there is also:

  1. Luxon interval human readable
  2. Difference between two dates in years, months, days in JavaScript
  3. How to get difference between 2 Dates in Years, Months and days using moment.js

and many others.

about 4 years ago · Juan Pablo Isaza Relatório

0

You mean, like moment.fromNow()

[Sometimes, it pays to read the documentation]

If that won't work for you, then something like

  • https://www.npmjs.com/package/pretty-ms

might.

But...

Consider migrating to Luxon — Moment.js is deprecated. Luxon is smaller, more elegant. More to point, it has a Duration that has a toFormat() method that will give you exactly what you are looking for.

duration.toFormat() docs

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