0

I am developing an LWC. I want to subtract two dates and get the number of days between them so that I can conditionally render HTML based on the result.One of the dates is a field Here's my current code that's not working. I am getting the output as NaN.

let today2 = new Date().toISOString().split('T')[0];
let renewalDate = this.accFields.Renewal_Date__c.value;
let daysFromRenewal = (this.today2 - this.renewalDate) / (24 * 60 * 60 * 1000);

Output:

today2 = 2023-08-20

renewalDate = 2024-03-09

daysFromRenewal = NaN

1 Answer 1

2

Both today2 and renewalDate are string, so you're dividing a string by a number, that's why the result is NaN.

You should use Date objects and leverage getTime() method that returns the number of milliseconds for this date since the epoch (since Jan 1, 1970, 00:00:00.000 GMT), then you can divide by the number of millisecond in a day (24 * 60 * 60 * 1000), finally, if you want an integer value, you should call Math.floor():

const today2 = new Date();
const renewalDate = new Date(this.accFields.Renewal_Date__c.value);
const daysFromRenewal = Math.floor((today2.getTime() - renewalDate.getTime()) / (24 * 60 * 60 * 1000));
console.log(daysFromRenewal);
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .