如何在 Luxon 中使用 diff 方法

How to use diff method in Luxon

我目前从日历控件获取日期并使用 luxon 添加天数、分钟数并将其更改为 LongHours 格式,如下所示: newValue :是我从前端(日历控件)获得的值

  let formattedDate: any;
  FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
  console.log(formattedDate);

  const formattedDateParsed = DateTime.fromJSDate(new Date(formattedDate));
  const newValueParsed = DateTime.fromJSDate(new Date(newValue));

  var diffInMonths = formattedDateParsed.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
  diffInMonths.toObject(); //=> { months: 1 }
  console.log(diffInMonths.toObject());

目前 formattedDateParsed 的格式为 'Null'

我能得到一些关于如何解析日期以便计算差异的帮助吗

这里发生了一些事情。

首先,FormattedDateformattedDate 是不同的变量,所以 formattedDate 没有被设置:

let formattedDate: any;
FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
console.log(formattedDate);

其次,您要转换为字符串,然后再转换回 DateTime,使用 Date 构造函数作为解析器,这不是一个好主意,因为 a) 没有必要,b) 浏览器不是超级一致关于他们可以解析哪些字符串。

相反,我们只转换一次:

const newValueParsed = DateTime.fromJSDate(new Date(newValue));
const laterDate = newValueParsed.plus({ days: 1, hours: 3, minutes: 13, seconds: 10 });
const diffInMonths = laterDate.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
diffInMonths.toObject(); // => {months: 0, days: 1, hours: 3, minutes: 13, seconds: 10}