jmarkatti
jmarkatti

Reputation: 661

Getting days difference between two dates in React.js

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}
 />

&nbsp;&nbsp;&nbsp;

<b>End Date</b>:
 <DatePicker
   selected={this.state.endDate}
   onChange={this.handleChangeEnd}
 />

 <div className="amount">
   {this.state.days}
 </div>

</div>
    );
  }
}

Upvotes: 3

Views: 7466

Answers (1)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4871

You have to call your daysLeft method when either of the startDate or endDate is updated so that it will also update the days in the state.

handleChangeStart(date) {
  this.setState({
    startDate: date
  }, () => this.daysLeft());
}


handleChangeEnd(date) {
  this.setState({
    endDate: date
  }, () => this.daysLeft());
}

For better code readability, you might want to change the method name from daysLeft to something more appropriate of the action like calculateDaysLeft, getDaysLeft or a better name that you can think of.

Edit:

This is another implementation based from @Sulthan's comment.

If the purpose of days is for presentation only, then you don't need to store it on the state. Instead you could get the calculated days inside the render method itself.

See working implementation here: https://codesandbox.io/s/4w1496rp4

import React from "react";
import ReactDOM from "react-dom";
import moment from "moment";
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()
    };
    this.handleChangeEnd = this.handleChangeEnd.bind(this);
    this.handleChangeStart = this.handleChangeStart.bind(this);
  }

  handleChangeStart(date) {
    this.setState({
      startDate: date
    });
  }

  handleChangeEnd(date) {
    this.setState({
      endDate: date
    });
  }

  calculateDaysLeft(startDate, endDate) {
    if (!moment.isMoment(startDate)) startDate = moment(startDate);
    if (!moment.isMoment(endDate)) endDate = moment(endDate);

    return endDate.diff(startDate, "days");
  }

  render() {
    const { startDate, endDate } = this.state;

    const daysLeft = this.calculateDaysLeft(startDate, endDate);
    return (
      <div>
        <h3>Get Difference between two dates in days</h3>
        <b>Start Date</b>:
        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChangeStart}
        />
        &nbsp;&nbsp;&nbsp;
        <b>End Date</b>:
        <DatePicker
          selected={this.state.endDate}
          onChange={this.handleChangeEnd}
        />
        <div className="amount">{daysLeft}</div>
      </div>
    );
  }
}

Upvotes: 1

Related Questions