简体   繁体   中英

Difference of days between two dates in React.JS using moment

I made a function which calculates difference between two dates, but i dont know how to take(?) data to it using inputs. I also tried to return diffInDays; and instead of that use this.setState({ diffInDays: diffInDays }) . I've tried many combinations but none of them gave me the right result.

calculate(dateFrom, dateTo) {
    if (!dateFrom || !dateTo) {
       return null;
    }
    const arrival = moment(dateFrom);
    const departure = moment(dateTo);
    if (arrival.isAfter(departure)) {
       return null;
    }
      const diffInDays = departure
      .endOf('day')
      .diff(arrival.startOf('day'), 'days');
    
      return diffInDays;
}

those are the inputs I created:

  • this one is for the beginning
<div className="form-group">
  <label htmlFor="dateFrom">Date From: </label>
  <input
    type="date"
    className="form-control"
    id="dateFrom"
    onChange={this.onChangeDateFrom}
    value={this.state.dateFrom}
    name="dateFrom"
   />
</div>
  • and this one is for the end
<div className="form-group">
    <label htmlFor="dateTo">Date to: </label>
    <input
    type="date"
    className="form-control"
    id="dateTo"
    onChange={this.onChangeDateTo}
    value={this.state.dateTo}
    name="dateTo"
    />
</div>

  • and this is the one where I want to see the difference
<div className="form-group">
   <label htmlFor="daysDiff">Days Difference: </label>
   <input
   type="number"
   className="form-control"
   id="daysDiff"
   required
   value={this.state.daysDiff}
   name="daysDiff"
   readOnly
   />
</div>

Picking the dates works fine. They also save in the MongoDB, the problem appears only with the difference of days.

You should use departure.diff(arrival) and for getting only day difference departure.diff(arrival,'days')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM