从版本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>
在 version 之前, Luxon1.9.0
中没有等价物。calendar()
在 DateTime 方法等效 => 输出 =>人性化部分中说明的For Moment 用户手册页:
Luxon 不支持这些,并且在相对时间格式提案登陆浏览器之前不会支持。
Operation | Moment | Luxon
---------------------------------------------------------------------------------------
"Calendar time" | calendar() | None (before 1.9.0) / toRelativeCalendar() (after 1.9.0)
如果需要,您可以自己编写一些东西,这里有一个自定义函数示例,它具有类似的 moment's 输出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 code,它肯定可以改进。