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
JavaScript
x
8
1
periodReserve = (e, idPark, title ) => {
2
let Start_Day = this.state.startDate && this.state.startDate.format(Formatdate);
3
let Start_Hour = this.state.time && this.state.time.format(formatHour);
4
let End_Day = this.state.endDate && this.state.endDate.format(Formatdate);
5
let End_Hour = this.state.timeEnd && this.state.timeEnd.format(formatHour);
6
let diff = this.state.timeEnd - this.state.startDate;
7
console.log(diff);}
8
The code for the first DatePicker and the TimePicker ( for the start )
JavaScript
1
12
12
1
<DatePicker
2
id="calendar"
3
className="TestIcon"
4
dateFormat='YYYY-MM-DD'
5
placeholderText="Date de fin"
6
selected={this.state.startDate}
7
onChange={this.handleChangeStart}/>
8
9
<TimePicker showSecond={false}
10
placeholder={time}
11
onChange={this.onChangeStart}> </TimePicker>
12
The code for the second dataPicker and TimePicker
JavaScript
1
11
11
1
<DatePicker
2
id="calendar"
3
className="TestIcon"
4
dateFormat='YYYY-MM-DD'
5
selected={this.state.endDate}
6
onChange={this.handleChangeEnd}/>
7
8
<TimePicker showSecond={false}
9
placeholder={timeEnd}
10
onChange={this.onChangeEnd}> </TimePicker>
11
Advertisement
Answer
Sample code using momentJS
JavaScript
1
12
12
1
this.state = {startDate:1519026163000, timeEnd:1519126755000} // example
2
3
const startDate = moment(this.state.startDate);
4
const timeEnd = moment(this.state.timeEnd);
5
const diff = timeEnd.diff(startDate);
6
const diffDuration = moment.duration(diff);
7
8
console.log("Total Duration in millis:", diffDuration.asMilliseconds());
9
console.log("Days:", diffDuration.days());
10
console.log("Hours:", diffDuration.hours());
11
console.log("Minutes:", diffDuration.minutes());
12
console.log("Seconds:", diffDuration.seconds());
JavaScript
1
1
1
<script src="https://momentjs.com/downloads/moment.js"></script>