luxon是否支持显示相对于给定时间的时间?
时刻具有“日历时间”功能:
https://momentjs.com/docs/#/displaying/calendar-time/
moment().calendar(null, {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});
使用luxon可以达到相同的效果吗?
答案 0 :(得分:2)
从1.9.0
版本开始,您可以使用toRelativeCalendar
:
返回该日期相对于今天的字符串表示形式,例如“昨天”或“下个月”平台支持
Intl.RelativeDateFormat
。
const DateTime = luxon.DateTime;
const now = DateTime.local();
// Some test values
[ now,
now.plus({days: 1}),
now.plus({days: 4}),
now.minus({days: 1}),
now.minus({days: 4}),
now.minus({days: 20}),
].forEach((k) => {
console.log( k.toRelativeCalendar() );
});
<script src="https://cdn.jsdelivr.net/npm/luxon@1.10.0/build/global/luxon.js"></script>
在版本1.9.0
之前,卢森堡没有calendar()
版本。
在DateTime方法等效项=>输出=> For Moment users部分中所述的Humanization手册页:
Luxon不支持这些功能,并且只有在Relative Time Format提案进入浏览器后才会提供。
Operation | Moment | Luxon --------------------------------------------------------------------------------------- "Calendar time" | calendar() | None (before 1.9.0) / toRelativeCalendar() (after 1.9.0)
如果需要,您可以自己编写一些内容,这里是一个自定义函数示例,其输出与矩量的calendar()
类似:
const DateTime = luxon.DateTime;
function getCalendarFormat(myDateTime, now) {
var diff = myDateTime.diff(now.startOf("day"), 'days').as('days');
return diff < -6 ? 'sameElse' :
diff < -1 ? 'lastWeek' :
diff < 0 ? 'lastDay' :
diff < 1 ? 'sameDay' :
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : 'sameElse';
}
function myCalendar(dt1, dt2, obj){
const format = getCalendarFormat(dt1, dt2) || 'sameElse';
return dt1.toFormat(obj[format]);
}
const now = DateTime.local();
const fmtObj = {
sameDay: "'Today'",
nextDay: "'Tomorrow'",
nextWeek: 'EEEE',
lastDay: "'Yesterday'",
lastWeek: "'Last' EEEE",
sameElse: 'dd/MM/yyyy'
};
// Some test values
[ now,
now.plus({days: 1}),
now.plus({days: 4}),
now.minus({days: 1}),
now.minus({days: 4}),
now.minus({days: 20}),
].forEach((k) => {
console.log( myCalendar(now, k, fmtObj) );
});
<script src="https://cdn.jsdelivr.net/npm/luxon@1.8.2/build/global/luxon.js"></script>
此代码从code时刻开始受到启发,可以肯定地加以改进。