1

StackOverflow 的好心人,我遇到了 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)
}

谢谢大家。

4

1 回答 1

1

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

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

演示

编辑有 luxon-calculating-time-difference-between-2-dates 的麻烦

于 2021-04-24T06:48:46.540 回答