Доступность времени с помощью Moment JS - PullRequest
0 голосов
/ 27 октября 2018

Я создаю планировщик встреч с раскрывающимся списком, используя раскрывающийся список Выберите, чтобы выбрать человека.Допустим, Джон Смит и Flatpickr выберут дату.Когда я выберу Джона Смита, он должен назначить встречу между 15:00 и 30 октября.Поэтому, если я хочу отобразить и отключить кнопку, он недоступен в период с 15:00 до 17:00, а остальные кнопки отображаются со временем, когда он доступен.Как я могу заняться этим?Есть ли NPM, который я могу установить?Время, с которым я буду сравнивать это с момента библиотеки JS.Я использую React Js, и время, которое я получаю от этого человека, происходит от вызова Ajax.

componentDidMount() {
    let id = this.props.userId || this.props.match.params.id

    const promise = userService.getUserIdNetwork(id)
    promise.then(response => {
        const coaches = []
        const coachItems = response.item
        coachItems.map(item => {
            coaches.push({
                value: item.connectionId
                , label: `${item.firstName} ${item.lastName}`
            })
            this.setState({
                options: coaches
                , requesterId: id
            })
        })
    })
    // array of objects that have start AND end datetimes
    //make the date with the appointment date
    const startAndEndTimes = [
        {startTime: moment().hour(12).minute(0).second(0), endTime: moment().hour(12).minute(59).second(59)}
      , {startTime: moment().hour(1).minute(0).second(0), endTime: moment().hour(1).minute(59).second(59)}      
      , {startTime: moment().hour(2).minute(0).second(0), endTime: moment().hour(2).minute(59).second(59)}      
      , {startTime: moment().hour(3).minute(0).second(0), endTime: moment().hour(3).minute(59).second(59)}      
      , {startTime: moment().hour(4).minute(0).second(0), endTime: moment().hour(4).minute(59).second(59)}      
      , {startTime: moment().hour(5).minute(0).second(0), endTime: moment().hour(5).minute(59).second(59)}      
      , {startTime: moment().hour(6).minute(0).second(0), endTime: moment().hour(6).minute(59).second(59)}      
      , {startTime: moment().hour(7).minute(0).second(0), endTime: moment().hour(7).minute(59).second(59)}      
      , {startTime: moment().hour(8).minute(0).second(0), endTime: moment().hour(8).minute(59).second(59)}      
      , {startTime: moment().hour(9).minute(0).second(0), endTime: moment().hour(9).minute(59).second(59)}           
      , {startTime: moment().hour(10).minute(0).second(0), endTime: moment().hour(10).minute(59).second(59)}           
      , {startTime: moment().hour(11).minute(0).second(0), endTime: moment().hour(11).minute(59).second(59)}           
      , {startTime: moment().hour(12).minute(0).second(0), endTime: moment().hour(12).minute(59).second(59)}           
    ]          
    console.log(startAndEndTimes)
      const promise2 = appointmentsService.getAppointmentByDay(id, 10, 26, 7)
      promise2.then(response => {
          console.log(response)
          response.items.forEach(timeObj => { //loops thru array of items to access appointmentDate by date. Coaches appointments
              console.log(timeObj.appointmentDate)
              debugger;
              let appBegins = timeObj.appointmentDate;
              let appEnds = timeObj.appointmentEndDate;
              // get appEndTime as well

              startAndEndTimes.forEach(arrTime => { // arr of times that will be compared to coaches times range
                  let slotBegins = arrTime.startTime._d
                  let slotEnds = arrTime.endTime._d
                  debugger;

                 if((appBegins > slotBegins) && (appBegins < slotEnds) || (appEnds < slotEnds) && (appEnds > slotBegins)){
                      return console.log("Not Available")
                  }else {
                      return console.log("Available Times")
                  }
              })
              this.setState({
                  dateFromApiCall: response.items
              })
          })

      })
          .catch(console.error)
  }

1 Ответ

0 голосов
/ 27 октября 2018

Вы можете использовать пакет moment-range (https://www.npmjs.com/package/moment-range/v/1.0.2), чтобы создать диапазон дат, а затем проверить, находится ли текущая дата в этом диапазоне, чтобы можно было отключить кнопку:

const start = moment('2018-10-27 21:40:00');
const end = moment('2018-10-27 22:40:00');
const now = moment();

const range  = moment().range(start, end);

range.contains(now); // Current time is within the range therefore disable button.
...