Home > other >  postman: How to add minutes to a dateTime while looping with JS?
postman: How to add minutes to a dateTime while looping with JS?

Time:06-03

I am trying to add 15 mins to a dateTime(2100-01-04T08:00:00) while looping. For each run I want to add 15 minutes , so it would be 2100-01-04T08:15:00 , 2100-01-04T08:30:00 and so on… I know I can do the below: var moment = require('moment'); moment().add(15, 'minutes').toISOString(); But this will add 15 minutes to the current moment time but I want to add 15 minutes to 2100-01-04T08:00:00.

Is this possible in postman?

CodePudding user response:

You can achieve this without using any third party libraries like momentJs. The default javascript Date object has methods for getting the minutes property for a date object - getMinutes() and also another method for updating this minutes property - setMinutes(). Combining them both, you can achieve your required answer.

let x = new Date('2100-01-04T08:00:00') 
for(let i = 0 ; i < 5; i   ){
  x.setMinutes(x.getMinutes() 15);
  console.log(x)
}

P.S, remove 'postman' from your question. It has nothing to do with the problem you are facing.

CodePudding user response:

You can easily create an addMinutes() function to add a number of minutes to a date, you can then use a while loop to loop until a specified end date is reached.

In the example below, we'll add 15 minutes to the date until the end date is reached.

function addMinutes(date, minutes) {
    let newDate = new Date(date);
    newDate.setMinutes(newDate.getMinutes()   minutes);
    return newDate;
}

let date = new Date('2100-01-04T08:00:00');
let endDate = new  Date('2100-01-04T09:00:00');

let deltaMinutes = 15;
while (date <= endDate) {
    console.log(date.toLocaleString('en-US'));
    date = addMinutes(date, 15);
}
.as-console-wrapper { max-height: 100% !important; }

  • Related