luxon 有问题,计算两个日期之间的时差

having trouble with luxon, calculating time difference between 2 dates

Whosebug 的好心人,我遇到了 luxon 的问题(我想我设置错误或做错了什么),现在它无法计算未来的日期(NaN 说),并且对于过去的日期考虑了年份,所以你会得到这样的结果:

[

我想让这段代码做的是关注月份和日期(忘记年份),如果过去的日期距今天的日期还有 7 天或不到 7 天,则说“过去的日期是 < = 一周”,稍后这将触发一个通知程序,它将在我的朋友和家人生日前一周通知我。

代码:

const isBirthdayThisWeek = (birthDate) => {
  const endDate = DateTime.now()
  const startDate = DateTime.fromISO(birthDate)
  const interval = Interval.fromDateTimes(startDate, endDate)
  const dateDifference = interval.length('days')
  const wholeNumberedDateDifference = Math.round(dateDifference)
  wholeNumberedDateDifference <= 7
    ? console.log('bday is in less than a week', wholeNumberedDateDifference)
    : wholeNumberedDateDifference > 7
      ? console.log('bday is more than in a week', wholeNumberedDateDifference)
      : console.log('something went wrong', wholeNumberedDateDifference)
}

提前谢谢大家。

您可以使用计算持续时间的大小。持续时间适用于未来和过去的两个时间间隔。将开始日期调整为与当前年份“对齐”,这样日期差异就不会跨越年份边界。

import { DateTime } from "luxon";

const startDate = DateTime.fromISO("2000-04-26").set({
  year: DateTime.now().get("year")
});
const diff = Math.abs(startDate.diffNow().as('day'));
const wholeNumberedDateDifference = Math.round(diff);
if (diff <= 7) {
  console.log("bday is in less than a week", wholeNumberedDateDifference);
} else {
  console.log("bday is more than in a week", wholeNumberedDateDifference);
}

输出

bday is in less than a week 2

演示