sandesh phuyal
sandesh phuyal

Reputation: 73

How can I set a time interval based on current date/time using Vue.js

Lets assume that current date/time is 03/29/2020 02:10 PM. Then i want to display 7 sets of time with fifteen minutes interval that will be 01:30 PM , 01:45 PM , 02:00 PM , 02:15 PM, 02:30 PM , 02:45 PM and 03:00 PM.

Current Date/Time =  03/29/2020 02:10 PM

<div :key="timeList">
      <button>{{timeList}}</button>
</div>

How can i display seven sets of time in timeList as 15 minutes interval for currentTime as

Upvotes: 1

Views: 1631

Answers (2)

RobG
RobG

Reputation: 147563

If the current time is 02:10, then the next 15 minute block starts at 02:15.

Anyway, you can use built–in formatting functions to get the appropriate format, e.g.

/* 
** @param {Date} date: date to use for time blocks
** @param {number} mins: length of time block in minutes
**        should be an even divisor of 60, e.g. 5, 10, 12, 15
** @param {number} num: number of values to return
** @returns {Array} array of strings formatted as hh:mm ap
*/
function getTimes(date, mins, num) {
  // Copy date so don't affect original
  let d = new Date(date);
  // Get start of next block
  let dMins = d.getMinutes();
  let nextMin = Math.ceil(dMins/mins) * mins; 
  // If in first minute of first block, add 1
  if (!(dMins%mins)) nextMin += mins;
    
  d.setMinutes(nextMin, 0, 0);
  let result = [];
  let opts = {hour:'2-digit', minute:'2-digit', hour12:true};
  
  while (num--) {
    result.push(d.toLocaleString('en', opts));
    d.setMinutes(d.getMinutes() + mins);
  }
  
  return result;
}

console.log(getTimes(new Date(), 15, 7));

Upvotes: 2

Anees Hameed
Anees Hameed

Reputation: 6564

I would recommend you use moment for this. Even though this can be done by adding little more lines using without moment, but adding moment to your project will save time and energy.

<div id="app">
  <div v-for="item in timeList" :key="timeList">
      <button>{{item}}</button>
  </div>
</div>
<script>
new Vue({
  el: '#app',
  ...
  ...
  data: {
     timeList: [
     ],
  },
 mounted: function(){
   const current = new moment();
   for(let i=0;i<5;i++){
      this.timeList.push(current.format("HH:mm"));
      current.add(15, "minutes");
   }

 }
})
</script>

Check moment here https://momentjs.com/docs/

Upvotes: 0

Related Questions