Search code examples
vue.jsvuejs2vue-clivue-cli-3

Vuejs: how to loop start time to multiply end time with var x


I have data start_time, end_time, x, and result. I want to display it in the select option, the first option is the initial data start_time, and continues to loop multiples of variable x and ends until the value is equal to end_time. here are the expectations.

enter image description here

Here my view:

<select class="form-control">
    <option>08:00:00</option>
    <option>08:15:00</option>
    <option>08:30:00</option>
    <option>08:45:00</option>
    <option>09:00:00</option>
    <option>...</option>
    <option>19:00:00</option>
</select>

This is my code:

data: function () {
    return {
        start_time: '08:00:00',
        end_time: '19:00:00',
        x: 15,
        result:'',
    }
},
computed:{
}

Solution

  • What you can do is create a computed property which returns an array of all the available time options given the start_time and the end_time constraints. Then loop it to your <option/> element using v-for.

      <select class="form-control">
        <option v-for="(time, index) in times" :key="index">{{time}}</option>
      </select>
    
    computed: {
      times() {
        // transform the start_time and end_time to Date for easier comparison.
        let startTime = new Date(`1/1/1970 ${this.start_time}`);
        const endTime = new Date(`1/1/1970 ${this.end_time}`);
    
        // This interval is in Minutes.
        const interval = this.x * 60000;
    
        // The result array where we will store the time
        const results = [];
    
        while (startTime.getTime() <= endTime.getTime()) {
          results.push(`${this.formatTime(startTime)}`);
          startTime = new Date(startTime.getTime() + interval);
        }
    
        return results;
      }
    },
    methods: {
      formatTime(date) {
        // format the date here...
        return '00:00:00';
      }
    }
    

    For formatting date, you can either use third-party library to do the job, or you can use vanilla javascript.

    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${hours}:${minutes}:${seconds}`;
    }
    

    Here is a working demo.