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
CodePudding user response:
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:


