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

Displaying time relative to a given using luxon library

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

Moment 具有 "Calendar time" 个特征:

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 实现同样的效果吗?

来自版本 1.9.0 you can use toRelativeCalendar

Returns a string representation this date relative to today, such as "yesterday" or "next month" platform supports 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 之前,Luxon 中没有 calendar() 等价物。

For Moment users manual page stated in the DateTime method equivalence => Output => Humanization 部分:

Luxon doesn't support these, and won't until the Relative Time Format proposal lands in browsers.

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>

这段代码大致灵感来源于code,肯定可以改进。