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

标签 javascript reactjs momentjs react-datepicker react-dates

你好,我想显示我从react-dates和momentjs获得的两个日期之间的差异。日期正在显示,但 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>
  )}
}

最佳答案

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

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

这将返回 3。

关于javascript - react-dates 与 moment js 的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912741/

相关文章:

javascript - 从日期中减去时间 - 时刻 js

Mustache 不评估函数内的 {{}}

javascript - 无法在 Google Maps Api v3 中添加标记

node.js - React npm run build,那是什么,为什么我们需要它?

javascript - 带有反应的谷歌分析不起作用

reactjs - React 应用程序的 CloudFront 缓存失效

javascript - currDateEnd.setHours 不是函数

javascript - Ruby on Rails 检查是否启用了 javascript

javascript - jQuery AJAX - 基于 PHP 页面数据的条件成功结果

javascript - 使用jQuery找出用ctrl键按下的键