HarryTgerman
HarryTgerman

Reputation: 107

react-dates date differnce with momentjs

Hello i want to display the difference between 2 dates which i get from react-dates with momentjs. The dates are getting displayed, but the const Diff shows NaN. I have done everything according to the docs of momentjs https://momentjs.com/docs/#/displaying/difference/

import React, { Component } from 'react';
import {Col,Grid, Image,Row, Form, ControlLabel, Button} from 'react-bootstrap'
import momentPropTypes from 'react-moment-proptypes';
import moment from 'moment';
import 'react-dates/initialize';
import { DateRangePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
moment.locale('pt-br');

class Details extends Component {

constructor (props){
  super(props)
  this.state={
    startDate: "",
    endDate: "",
    focusedInput: "",
  }
render() {
    const endDateString = this.state.endDate && this.state.endDate.format('DD-MM-YYYY');
    const startDateString = this.state.startDate && this.state.startDate.format('DD-MM-YYYY');
    const startDateArr = startDateString.split("-");
    const endDateArr = endDateString.split("-");
    const a = moment(startDateArr);
    const b = moment(endDateArr);
    const Diff =  a.diff(b, 'days');

    return (
      <div>
         <DateRangePicker
                          startDate={this.state.startDate} // momentPropTypes.momentObj or null,
                          endDate={this.state.endDate} // momentPropTypes.momentObj or null,
                          onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired,
                          focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
                          onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
                          endDatePlaceholderText={"Bis"}
                          startDatePlaceholderText={"Ab"}
                          displayFormat={"DD/MM/YYYY"}
                        />
                      {startDateString}
                      <br/>
                      {endDateString}
                      <br/>
                      {Diff}
     </div>
  )}
}

Upvotes: 0

Views: 2349

Answers (2)

Alia Anis
Alia Anis

Reputation: 1495

When you trying to use moment.js functions, make sure you make them moment objects. I used it like this

let date1=moment();
let date2=moment().add(3,"days");
let daysSpan={moment(date2).diff(moment(date1), 'days')};

This shall return 3.

Upvotes: 1

TLadd
TLadd

Reputation: 6894

If you look at the moment docs for building a moment object from an array, the ordering is [year, month, day ...], but you are providing [day, month, year]. If you change the format call to 'YYYY-MM-DD', I think your code would work.

Upvotes: 0

Related Questions