How to use diff method in Luxon
Asked Answered
S

1

10

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

Scraper answered 9/8, 2019 at 4:32 Comment(3)
Can you provide a sample value of newValue?Stinky
Friday, January 2, 1970, 8:43:10 AM India Standard TimeScraper
Is that a string or a JavaScript Date? If it is a Js Date I think you can remove the new Date, while if it is a string I fear new Date cannot parse it correctly, you can probably use fromFormatStinky
L
7

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}
Lopez answered 13/8, 2019 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.