使用luxon库显示相对于给定的时间



luxon是否支持显示相对于给定时间的功能?

Moment具有"日历时间"功能:

https://momentjs.com/docs/#/displaying/calendar-时间/

moment().calendar(null, {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});

我能用luxon实现同样的效果吗?

从版本1.9.0开始,您可以使用toRelativeCalendar:

返回此日期相对于今天的字符串表示形式,例如"昨天";或";下个月";平台支持CCD_ 3。

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之前,Luxon中没有等效的calendar()

DateTime方法等效性中所述的For Moment用户手册页面=>输出=>人性化部分:

Luxon不支持这些,而且在相对时间格式提案登陆浏览器之前不会支持。

Operation       | Moment     | Luxon
---------------------------------------------------------------------------------------
"Calendar time" | calendar() | None (before 1.9.0) / toRelativeCalendar() (after 1.9.0)

如果你需要,你可以自己写一些东西,这里有一个自定义函数示例,它有类似于moment的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>

这段代码大致受到了moment代码的启发,它肯定可以改进

最新更新