javascript - Create an array with time intervals and add 2 hours - Stack Overflow

I need to create an array of elements in javascript, which add 2 hours to a certain time I set.I give

I need to create an array of elements in javascript, which add 2 hours to a certain time I set. I give an example. The time is

14:00.

I need, to create an array that contains all 30 minute intervals up to 16:00.
Ex

14:00
14:30
15:00
15:30

I need to create an array of elements in javascript, which add 2 hours to a certain time I set. I give an example. The time is

14:00.

I need, to create an array that contains all 30 minute intervals up to 16:00.
Ex

14:00
14:30
15:00
15:30
Share Improve this question asked Jan 19, 2022 at 15:15 PeraDevPeraDev 515 bronze badges 2
  • Nice, and what is your attempt at that? What research have you done? – Jeremy Thille Commented Jan 19, 2022 at 15:37
  • Read How to Ask and minimal reproducible example. We fix code that you honestly tried to fix yourself -- we don't write it for you. – zer00ne Commented Jan 19, 2022 at 15:59
Add a ment  | 

4 Answers 4

Reset to default 4

Here is a function that produces the time specifications as strings. It can take an optional second argument to specify the end-time (16:00 in your question).

Two utility functions convert a time string to (and from) a number of minutes.

Finally, the result array is created with Array.from:

const toMinutes = str => str.split(":").reduce((h, m) => h * 60 + +m);

const toString = min => (Math.floor(min / 60) + ":" + (min % 60))
                       .replace(/\b\d\b/, "0$&");

function slots(startStr, endStr="16:00") {
    let start = toMinutes(startStr); 
    let end = toMinutes(endStr);
    return Array.from({length: Math.floor((end - start) / 30) + 1}, (_, i) =>
        toString(start + i * 30)
    );
}

console.log(slots("14:00"));

What I would do was to create two methods: addTime and createDateArray.

On addTime function we use to convert a timestamp into a Date object so it is easier for you to manage rather than an 14:00 string.

const addTime = (_dateTimestamp, addHours, addMinutes, addSeconds) => { 
 const date = new Date();
 date.setTime( _dateTimestamp );
 
 const newDate = new Date();
 if(addHours) newDate.setHours( date.getHours() + addHours );
 if(addMinutes) newDate.setMinutes( date.getMinutes() + addMinutes );
 if(addSeconds) newDate.setSeconds( date.getSeconds() + addSeconds );
 
 return newDate;
}

const createDateArray = (date, minuteInterval, amount) => { 
  let array = [];
  for(let i = 1; i <= amount; i++) {
    const time = addTime( date, 0, minuteInterval * i, 0);
    array.push( time );
  }
  return array;
}

const dateToIncrement = new Date().getTime();
const minutesInterval = 30; // every 30 minutes
const amountTimes = 10; // will run through 10 times, so it'll calculate the minutes 10 times

const result = createDateArray( dateToIncrement, minutesInterval, amountTimes );

console.log(result);

You can also use the addTime function for other properties like hours and seconds if you wish by setting the second and last argument of the method.

I hope the code above makes sense and you can make use of it.

You can create a basic function like this :

   function getTimes(start) {
    start = parseInt(start) * 2 + (+start.slice(-2) > 0);
    end = start+60/12;
    return Array.from({length: end - start}, (_, i) =>
        (((i + start) >> 1) + ":" + ((i + start)%2*3) + "0").replace(/^\d:/, "0$&"));
};

And use with :

getTimes("14:00");

Here is function that generates time slots in specified boundaries, it's similar to trincot's answer, but doesn't use regex and works for the edge cases:

const timeStringToMinutes = (timeStr, separator) => timeStr.split(separator).reduce((h, m) => h * 60 + +m);

const minutesToTimeString = (minutes, separator) => {
    const minutesPart = (minutes % 60).toString().padStart(2, "0");
    const hoursPart = Math.floor(minutes / 60).toString().padStart(2, "0");
    return hoursPart + separator + minutesPart;
}

function generateTimeSlots(startStr, endStr, periodInMinutes, separator = ":") {
    let startMinutes = timeStringToMinutes(startStr, separator);
    let endMinutes = timeStringToMinutes(endStr, separator);
    const oneDayInMinutes = 1440;
    if (endMinutes >= oneDayInMinutes)
        endMinutes = oneDayInMinutes - 1;
    if (startMinutes <= 0)
        startMinutes = 0;

    return Array.from({ length: Math.floor((endMinutes - startMinutes) / periodInMinutes) + 1 }, (_, i) =>
        minutesToTimeString(startMinutes + i * periodInMinutes, separator)
    );
}

console.log(generateTimeSlots("14:00", "15:30", 30));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744979961a4604382.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信