I'm working with date picker in react and have implemented Start and end date which works fine. now I need to get the days difference between the two dates(between Start and End dates).
Here is the problem. Each time I select the two dates to get the difference in days, it only shows the initialize 0 days. I have resorted to a solution here
But still, show 0 days on date select element. No error message is shown on the console.
Here is my code
//install the following
//npm i --save react-datepicker
//npm i --save moment
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
class CheckDate extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate: new Date(),
endDate: new Date(),
days: 0,
};
this.handleChangeEnd = this.handleChangeEnd.bind(this);
this.handleChangeStart = this.handleChangeStart.bind(this);
this.daysLeft = this.daysLeft.bind(this);
}
handleChangeStart(date) {
this.setState({
startDate: date
});
}
handleChangeEnd(date) {
this.setState({
endDate: date
});
}
daysLeft() {
let {startDate, endDate} = this.state;
console.log(startDate);
console.log(endDate);
let amount = endDate.diff(startDate, 'days');
this.setState({
days: amount
});
}
render() {
return (
<div>
<h3>Get Difference between two dates in days</h3>
<b>Start Date</b>:
<DatePicker
selected={this.state.startDate}
onChange={this.handleChangeStart}
/>
<b>End Date</b>:
<DatePicker
selected={this.state.endDate}
onChange={this.handleChangeEnd}
/>
<div className="amount">
{this.state.days}
</div>
</div>
);
}
}