Skip to content
Advertisement

Calculate the difference between two dates in javascript using react

I’m trying to get the difference between two date in react whith two datepicker and two timepicker ( a react component ). The date is for a booking and I want to get the duration by substract the “end date” with “start date”, but when I subtract two date whith more than 24 hours I have a -152 or a value that not corresponding to the real duration.

The code

periodReserve = (e, idPark, title ) => {
let Start_Day = this.state.startDate && this.state.startDate.format(Formatdate);
let Start_Hour = this.state.time && this.state.time.format(formatHour);
let End_Day = this.state.endDate && this.state.endDate.format(Formatdate);
let End_Hour = this.state.timeEnd && this.state.timeEnd.format(formatHour);
let diff = this.state.timeEnd - this.state.startDate;
console.log(diff);}

The error

The code for the first DatePicker and the TimePicker ( for the start )

<DatePicker
  id="calendar"
  className="TestIcon"
  dateFormat='YYYY-MM-DD'
  placeholderText="Date de fin"
  selected={this.state.startDate}
  onChange={this.handleChangeStart}/>

<TimePicker showSecond={false}
     placeholder={time}
     onChange={this.onChangeStart}> </TimePicker>

The code for the second dataPicker and TimePicker

<DatePicker
    id="calendar"
    className="TestIcon"
    dateFormat='YYYY-MM-DD'
    selected={this.state.endDate}
    onChange={this.handleChangeEnd}/>

 <TimePicker showSecond={false}
  placeholder={timeEnd}
  onChange={this.onChangeEnd}> </TimePicker>

Advertisement

Answer

Sample code using momentJS

this.state = {startDate:1519026163000, timeEnd:1519126755000} // example

const startDate = moment(this.state.startDate);
const timeEnd = moment(this.state.timeEnd);
const diff = timeEnd.diff(startDate);
const diffDuration = moment.duration(diff);

console.log("Total Duration in millis:", diffDuration.asMilliseconds());
console.log("Days:", diffDuration.days());
console.log("Hours:", diffDuration.hours());
console.log("Minutes:", diffDuration.minutes());
console.log("Seconds:", diffDuration.seconds());
<script src="https://momentjs.com/downloads/moment.js"></script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement