How to use diff method in Luxon

pankaj picture pankaj · Aug 9, 2019 · Viewed 11.5k times · Source

I currently get a date from calendar control and using luxon I add days, minutes to it and change it to LongHours format like below: 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());

Currently the formattedDateParsed is coming as 'Null'

Can I get some help as how to parse the date so that diff can be calculated

Answer

snickersnack picture snickersnack · Aug 13, 2019

A few things going on here.

First, FormattedDate and formattedDate are different variables, so formattedDate isn't being set:

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);

Second, you are converting to a string and then back into a DateTime, using the Date constructor as a parser, which isn't a great idea because a) it's unnecessary, and b) browsers aren't super consistent about which strings they can parse.

Instead, let's just convert once:

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}