计算时差时出错

时间:2017-11-29 14:08:27

标签: javascript jquery html jquery-ui

快照中提到了实际输出和预期输出:[案例1的快照] [1] [案例2的快照] [2]。 我在计算开始时间和结束时间之间的时间差时遇到错误。错误:

  1. 如果开始时间大于结束时间,则计算错误。
  2. 如果包含周末且开始时间大于结束时间。
  3. 请建议如何解决我的代码中的错误。

    
    
    // Wire up Date and DateTime pickers (with default values)
      $("#start").datetimepicker();
      $("#end").datetimepicker();
      $("#workday_start").timepicker({
        hour: 8
      }).val("8:00");
      $("#workday_end").timepicker({
        hour: 17
      }).val("17:00");
    
      // Calculate the number of hours worked
      $("#calculate").click(function() {
        // Are all fields complete?
        var allFieldsComplete = $('.data input').filter(function() {
          return $(this).val().toString().length == 0;
        }).length == 0;
    
        // Ensure all fields are present
        if (allFieldsComplete) {
    
          // Capturing the input dates
          var startDate = moment($("#start").val());
          var endDate = moment($("#end").val());
          var daysDiff = endDate.diff(startDate, 'days');
    
          // Capturing the input times
          var startTime = startDate.hours();
          var endTime = endDate.hours();
          var timeDiff;
    
          var operational_hr_start = new Date("1/1/0001 " + $("#workday_start").val()).getHours() + (new Date("1/1/0001 " + $("#workday_start").val()).getMinutes() / 60)
          var operational_hr_end = new Date("1/1/0001 " + $("#workday_end").val()).getHours() + (new Date("1/1/0001 " + $("#workday_end").val()).getMinutes() / 60);
          var includeWeekends = $('input[type=checkbox]').prop('checked');
    
          if (startTime < operational_hr_start) {
            startTime = operational_hr_start;
          }
    
          if (endTime > operational_hr_end) {
            endTime = operational_hr_end;
          }
          timeDiff = endTime - startTime;
          if (daysDiff > 0) {
    
        var response= workingHoursBetweenDates(startDate, endDate, operational_hr_start, operational_hr_end, includeWeekends);
    $("#result").val(response);
          } else if (daysDiff === 0) {
            var dayNo = startDate.day();
            if (dayNo === 0 || dayNo === 6) {
              alert('Weekend!!!');
              return;
            } else {
              if (timeDiff > 0) {
                alert('Total hours worked: ' + timeDiff);
              } else {
                alert('End time must be greater than start time!!!');
              }
            }
          } else {
            alert('End date must be greater than start date!!!');
          }
        } else {
          // One or more of the fields is undefined or empty
          alert("Please ensure all fields are completed.");
        }
      });
    });
    
    // Simple function that accepts two parameters and calculates the number of hours worked within that range
    function workingHoursBetweenDates(startDate, endDate, operationalHourStart, operationalHourEnd, includeWeekends) {
      var incrementedDate = startDate;
      var daysDiff = endDate.diff(startDate, 'days');
      var workingHrsPerDay = operationalHourEnd - operationalHourStart;
      var startHrs = startDate.hours(),
          endHrs = endDate.hours(),
          totalHoursWorked = 0;
      if (startDate.hours() < operationalHourStart) {
        startHrs = operationalHourStart;
      }
      if (endDate.hours() > operationalHourEnd) {
        endHrs = operationalHourEnd;
      }
      /*
       * The below block is to calculate the duration for the first day
       *
       */
      {
        totalHoursWorked = operationalHourEnd - startHrs;
        if (startDate.day() === 0 || startDate.day() === 6) {
          totalHoursWorked = 0;
          if (includeWeekends) {
            totalHoursWorked = operationalHourEnd - startHrs;
          }
        }
        incrementedDate = incrementedDate.add(1, 'day');
      }
      /*
       * The below if block is to calculate the duration for the last day
       *
       */
      {
        var lastDayWorkHrs = endHrs - operationalHourStart;
        totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
        if (endDate.day() === 0 || endDate.day() === 6) {
          if (includeWeekends) {
            totalHoursWorked = totalHoursWorked + lastDayWorkHrs;
          } else {
            totalHoursWorked = totalHoursWorked - lastDayWorkHrs;
          }
        }
      }
    
      // The below for block calculates the total no. of hours excluding weekends. Excluding first and last day
      for (var i = 1; i < daysDiff; i++) {
        /*
         * Weekname mapping. There are default week
         * numbers (i.e., 0 to 6. 0 means Sunday, 1 means Monday, ... 6 means Saturday)
         * which are returned by moment library.
         *
         */
        if (incrementedDate.day() === 0 || incrementedDate.day() === 6) {
          // Do nothing
          if (includeWeekends) {
            totalHoursWorked = totalHoursWorked + workingHrsPerDay;
          }
        } else {
          totalHoursWorked = totalHoursWorked + workingHrsPerDay;
        }
        incrementedDate = incrementedDate.add(1, 'day');
      }
      return totalHoursWorked;
    }
    &#13;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.js"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.css" rel="stylesheet"/>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
    
          <pre>Variables</pre>
          <table>
            <tr>
              <th>START</th>
              <th>END</th>
              <th>WORKDAY START</th>
              <th>WORKDAY END</th>
            <th>Result</th>
              <th>INCLUDE WEEKENDS?</th>
            </tr>
            <tr class='data'>
              <th><input id='start' /></th>
              <th><input id='end' /></th>
              <th><input id='workday_start' /></th>
              <th><input id='workday_end' /></th>
            <th><input id='result' value=" "/></th>
              <th><input id='include_weekends' type='checkbox' /></th>
            </tr>
          </table>
          <hr />
          <input id='calculate' type='button' value='Calculate Hours Worked' />
    &#13;
    &#13;
    &#13;

0 个答案:

没有答案