比较按日期搜索(ReactJS)

时间:2017-10-23 07:54:36

标签: javascript reactjs datepicker momentjs date-range

我实现了一个允许根据所选日期进行搜索的组件。

我的问题是我无法比较日期。例如,如果所选日期相同,则在数据库中的日期之前,之后,或数据库的数据之间选择2个日期。

我使用了材料ui的组件datepicker和moment.js的插件,但我的印象是插件的功能没有返回给我我想要的东西,因为它总是返回我的假,因此不适合我的条件

import React from 'react';
import moment from 'moment';
import { extendMoment } from 'moment-range';
import 'moment/locale/fr'


let DateTimeFormat;
if (areIntlLocalesSupported(['fr'])) {
  DateTimeFormat = global.Intl.DateTimeFormat;
} else {
    const IntlPolyfill = require('intl');
    DateTimeFormat = IntlPolyfill.DateTimeFormat;
    require('intl/locale-data/jsonp/fr');
    require('intl/locale-data/jsonp/fa-IR');
}

const m = extendMoment(moment);

class SearchItemByDateComponent extends React.Component {
  constructor(props){
    super(props);

    this.state = {
        searchTerm: '',
        currentData: this.props.items,
        rangeDate: [],
        tabDate: []
    };
  }

  handleDate = (e, date) => {
    let dateR;
    let oldDate;
    let newDate;   
      dateR = m(date).locale('fr').format('L');
      if(this.state.tabDate != dateR){
          oldDate = this.state.tabDate;
          newDate = [...oldDate, dateR]

          if(newDate.length === 2){
              //IF RANGE = 2 dates chosen : isBetween
              this.setState({rangeDate: newDate})
          } else {
              //1 date chosen : isSame, isAfter, isBefore
              this.setState({tabDate: newDate})
          }
      }
  }

  render(){
    let listItem;
    let currentDate;
    let myDateDB;
    let dateChosen;

    listItem = this.props.items;
    // return list of last update Item (date)
    currentDate = listItem.map((item)=>{
        return item.lastUpdateTime
    })

   for(let i=0; i < currentDate.length; i++){
      if(currentDate[i] != 0){
          //format date lastupdate from db
          myDateDB =    m.unix(currentDate[i]).locale('fr').format('L');

          dateChosen = m(...this.state.tabDate);

          if(myDateDB.isAfter(dateChosen){
              console.log('after')
          } else if(myDateDB.isBefore(dateChosen){ 
              console.log('before')
          } else {
              console.log('same')
          }
      }
    }

    return(
      <div>
        <DatePicker
            hintText="Date début"
            DateTimeFormat={DateTimeFormat}
            okLabel="OK"
            cancelLabel="Annuler"
            locale="fr"
            onChange={this.handleDate}
        />
      <div>
    )
  }
}

0 个答案:

没有答案