繁体   English   中英

react-dates与moment.js的日期差异

[英]react-dates date differnce with momentjs

您好,我想显示我用momentjs从react-dates得到的两个日期之间的差异。 将显示日期,但const Diff显示NaN。 我已经根据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>
  )}
}

如果您查看用于从数组构建矩对象的矩文档 ,则顺序为[年,月,日...],但您提供的是[年,月,年]。 如果您将格式调用更改为“ YYYY-MM-DD”,我认为您的代码可以使用。

当您尝试使用moment.js函数时,请确保使它们成为矩对象。 我这样用

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

这将返回3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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