首页 > 解决方案 > 如何在 Luxon 中使用 diff 方法

问题描述

我目前从日历控件中获取日期,并使用 luxon 添加天数、分钟数并将其更改为 LongHours 格式,如下所示: newValue : is value I get from frontend(calendar control)

  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”的形式出现

我可以就如何解析日期获得一些帮助,以便可以计算差异

标签: javascriptluxon

解决方案


这里发生了一些事情。

首先,FormattedDate并且formattedDate是不同的变量,所以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}

推荐阅读