JS格式化时间
Format time in JS
所以我正在创建一个用户信息命令
我用moment.js表示相对时间
moment(timestamp).fromNow() \ 2 years ago
有没有办法像2 years x days, x seconds ago etc
那样格式化
你是说,像moment.fromNow()
[有时,它支付给 read the documentation]
如果这对你不起作用,那么
可能。
但是...
考虑迁移到 Luxon — Moment.js is deprecated. Luxon is smaller, more elegant. More to point, it has a Duration
,它有一个 toFormat()
方法,可以准确地满足您的需求。
我认为 Moment.js 没有简单的方法来做到这一点。
但是,使用 Luxon(Moment.js 的后继者)您可以创建一个间隔,将其转换为持续时间,然后格式化值。例如。获取从 ECMAScript 纪元到现在的年月日:
// 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>
注意还有:
- Difference between two dates in years, months, days in JavaScript
- How to get difference between 2 Dates in Years, Months and days using moment.js
所以我正在创建一个用户信息命令
我用moment.js表示相对时间
moment(timestamp).fromNow() \ 2 years ago
有没有办法像2 years x days, x seconds ago etc
你是说,像moment.fromNow()
[有时,它支付给 read the documentation]
如果这对你不起作用,那么
可能。
但是...
考虑迁移到 Luxon — Moment.js is deprecated. Luxon is smaller, more elegant. More to point, it has a Duration
,它有一个 toFormat()
方法,可以准确地满足您的需求。
我认为 Moment.js 没有简单的方法来做到这一点。
但是,使用 Luxon(Moment.js 的后继者)您可以创建一个间隔,将其转换为持续时间,然后格式化值。例如。获取从 ECMAScript 纪元到现在的年月日:
// 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>
注意还有:
- Difference between two dates in years, months, days in JavaScript
- How to get difference between 2 Dates in Years, Months and days using moment.js