3

Currently, I want to find a difference between two dates in months in LWC.

I am getting a difference as 'Nan'.

Here is the playground link

Below is the screenshot for your reference

enter image description here

2 Answers 2

10

The event.target.value is a string, not a date. You need to convert the value to date first then you need to subtract it.

import { LightningElement, track } from 'lwc';

export default class LightningExampleInputDate extends LightningElement {

    @track date1;
    @track date2;
    @track result;


    datehandler1(event) {
        this.date1 = new Date(event.target.value);
        console.log(event.target.value)
    }
    datehandler2(event) {
        this.date2 = new Date(event.target.value);
        console.log(event.target.value);
    }
    resulthandler() {
        this.result = this.date2 - this.date1; 
        /// this.result is in millisceonds you might need to convert it to days using below formula
        //this.result = parseInt(this.result/ (1000*60*60*24));
        console.log(this.result);
    }
}

HTML

<template>
    <lightning-input type="date" onchange={datehandler1} name="input1" label="Enter a date" ></lightning-input>
      <lightning-input type="date" onchange={datehandler2} name="input1" label="Enter a date" ></lightning-input>
 
     <button onclick={resulthandler}>Check result </button>
    Result -- {result}

</template>

Playground Link

2
  • Thank you @rahul .It works Commented Dec 30, 2019 at 11:19
  • 1
    please accept the answer if it is working for you. Commented Dec 30, 2019 at 11:20
0

The below code will give you difference between two dates in days. You can divide the final result by 30 then you will get it in months.

this.startDate=event.target.value;//get it from onchange
this.endDate=event.target.value;//get it from onchange


var date1=new Date(this.startDate);
var date2=new Date(this.endDate);
      
var dateDiff=(date2.getTime()-date1.getTime())/1000;//difference in mili seconds
dateDiff=dateDiff/(60*60*24);
console.log('inside diff date:'+dateDiff);

You must log in to answer this question.

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