Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use diff method in Luxon

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

like image 667
pankaj Avatar asked Aug 09 '19 04:08

pankaj


1 Answers

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}
like image 195
snickersnack Avatar answered Oct 23 '22 04:10

snickersnack