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

212
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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