Home > Mobile >  new Date generate new for each day of the week
new Date generate new for each day of the week

Time:10-12

I want to generate an array using new date for each day of the week, for example have an array for all the mondays that will appear in the next 60 days and so on for all the week days

  const availableTimeslots = [0, 1, 2, 3, 4, 5].map((id) => {
    return {
      id,
      startTime: new Date(new Date(new Date().setDate(new Date().getDate()   id)).setHours(9, 0, 0, 0)),
      endTime: new Date(new Date(new Date().setDate(new Date().getDate()   id)).setHours(17, 0, 0, 0)),
    };
  });

This will generate a list of days for the next 6 days , but I want to manually change the setHours attribute depending on day. For example I want that all the mondays to be from setHours(9, 0, 0, 0) to setHours(15, 0, 0, 0)) and so on.

CodePudding user response:

You could create an array called perhaps daysAndTimes to specify the start and end times for each day of the week.

Then when you are generating the data, you look up the start and end time by dow and pass this to the setHours function.

// The total number of days to generate
const dayCount = 14;

// The start and end time for each day of the week, edit as needed...
const daysAndTimes = [
    { id: 0, name: 'Sunday', start: [8, 0, 0, 0], end: [14, 0, 0, 0]},
    { id: 1, name: 'Monday', start: [9, 0, 0, 0], end: [15, 0, 0, 0]},
    { id: 2, name: 'Tuesday', start: [10, 0, 0, 0], end: [16, 0, 0, 0]},
    { id: 3, name: 'Wednesday', start: [11, 0, 0, 0], end: [7, 0, 0, 0]},
    { id: 4, name: 'Thursday', start: [12, 0, 0, 0], end: [18, 0, 0, 0]},
    { id: 5, name: 'Friday', start: [13, 0, 0, 0], end: [19, 0, 0, 0]},
    { id: 6, name: 'Saturday', start: [14, 0, 0, 0], end: [20, 0, 0, 0]}
]

const availableTimeslots = [...new Array(dayCount).keys()].map(id  => {
  const date = new Date(new Date().setDate(new Date().getDate()   id));
  const dow = date.getDay();
  return {
    id,
    startTime: new Date(new Date(date).setHours(...daysAndTimes[dow].start)),
    endTime: new Date(new Date(date).setHours(...daysAndTimes[dow].end)),
  };
});

console.log('Time slots:');

console.log('Id'.padEnd(6), 'Day'.padEnd(10), 'Start'.padEnd(22), 'End')
for(let timeSlot of availableTimeslots) {
  console.log((timeSlot.id   '').padEnd(6), timeSlot.startTime.toLocaleString('en', { weekday: 'long'} ).padEnd(10), timeSlot.startTime.toLocaleString('sv').padEnd(22), timeSlot.endTime.toLocaleString('sv'))
}
.as-console-wrapper { max-height: 100% !important; }

  • Related