Auto-Calculating End Date from Start Date and Period Duration in el-date-picker

updateEndDate(selectedTime) {
  if (this.scheduleData.phaseNature === 'point') {
    this.scheduleData.finishDate = selectedTime;
  } else {
    this.computeFinishDate();
  }
},
handleDurationBlur(event) {
  if (this.scheduleData.phaseNature !== 'point' && this.scheduleData.startDate && event.target.value) {
    this.computeFinishDate();
  }
},
computeFinishDate() {
  if (this.scheduleData.startDate && this.scheduleData.phaseLength) {
    const start = new Date(this.scheduleData.startDate);
    const inputValue = parseFloat(this.scheduleData.phaseLength);
    if (!isNaN(inputValue) && inputValue > 0) {
      // Convert half-months to days (1 unit = 15 days)
      const totalDays = Math.floor(inputValue * 15);
      const resultDate = new Date(start);
      resultDate.setDate(start.getDate() + totalDays);
      this.scheduleData.finishDate = resultDate.getTime();
    } else {
      this.scheduleData.finishDate = '';
    }
  }
}

Handling Manual Date Entry and Formatting

Since the backend expects timestamps, the following watcher normalizes manually typed date strings (e.g., 20240715) into a standard format (e.g., 2024-07-15) for processing.

watch: {
  scheduleData: {
    handler(updatedVal) {
      if (updatedVal.startDate && updatedVal.startDate !== '') {
        // Check if the string is a compact format without dashes
        if (typeof updatedVal.startDate === 'string' && updatedVal.startDate.indexOf('-') === -1) {
          let dateStr = updatedVal.startDate;
          const dashPositions = [4, 6];
          const separator = '-';
          for (let i = dashPositions.length - 1; i >= 0; i--) {
            const pos = dashPositions[i];
            dateStr = dateStr.substring(0, pos) + separator + dateStr.substring(pos);
          }
          this.scheduleData.startDate = dateStr;
        }
      } else {
        this.scheduleData.startDate = '';
      }
    },
    immediate: true,
    deep: true
  }
}

Tags: Vue.js Element UI Date Handling Frontend Logic Form Validation

Posted on Wed, 12 Aug 2026 16:51:53 +0000 by nodster