Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Task: Add 15 minutes and 20 minutes patterns to a given time. [08:00:00]

Increment the time by 20 minutes, plus add every quarter hour to it.

What I have tried:

JavaScript
    let x = new Date('2100-01-05T08:00:00')
    let y = new Date('2100-01-05T08:00:00')
    var expectedTime = []
    
    for (let i = 0; i < 10; i++) {
       x.setMinutes(x.getMinutes() + 15);
       var time1 = x.toString().split(' ')[4]
       expectedTime.push(time1)
       y.setMinutes(y.getMinutes() + 20);
       var time2 = y.toString().split(' ')[4]
       expectedTime.push(time2)
    }
    console.log(expectedTime)
/* 
current output is: 

"08:15:00" "08:20:00" "08:30:00" "08:40:00" "08:45:00" "09:00:00" "09:00:00" "09:20:00" "09:15:00" "09:40:00" "09:30:00" "10:00:00" "09:45:00" "10:20:00" "10:00:00" "10:40:00" "10:15:00" "11:00:00" "10:30:00" "11:20:00"

What I need is as below: 

"08:00:00" "08:15:00" "08:20:00" "08:30:00" "08:40:00" "08:45:00" "09:00:00" "09:15:00" "09:20:00" "09:30:00" "09:40:00" "09:45:00" "10:00:00" "10:15:00" "10:20:00" "10:30:00" "10:40:00" "10:45:00" "11:00:00" "11:15:00"
/*
Posted
Updated 15-Jun-22 10:27am

1 solution

Both the 15 and 20 minute intervals are dividable by five minutes. Declare a variable outside of the for loop and keep adding five minutes every iteration, test if the minutes are dividable by 15 or 20 and, if true, push them to expected time.

let x = new Date('2100-01-05T08:00:00')
var expectedTime = []

for (let i = 0; i < 10; i++) {
	var m = x.getMinutes();
  if (m % 15 === 0 || m % 20 === 0) expectedTime.push(x.toString().split(' ')[4]); 
  x.setMinutes(x.getMinutes() + 5);
}
console.log(expectedTime);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900