Search code examples
javascript

How to create array of dates starting from today to next six dates?


I want an array of dates starting from today to next six days, so it must contain an object representing the which day like monday.. and date in 2-dgit number

const date = new Date();
let option = {
    weekday: 'long',
    day: '2-digit'
};
let date_details = date.toLocaleDateString('en-US', option).split(' ');
let dataslot = [
    {
        day: date_details[0], //'Wednesday',
        date: date_details[1] //'29'
    }
];

This is an example for one day, but i expect till next 6 six days

How do i get the next six days from today in that format ?


Solution

  • To generate an array of dates starting from today to the next six days with each object representing the day of the week and the date in two-digit format, you can use the following approach:

    const date = new Date();
    let options = {
        weekday: 'long',
        day: '2-digit'
    };
    let dataslot = [];
    
    // Function to add days to the current date
    function addDays(date, days) {
        let result = new Date(date);
        result.setDate(result.getDate() + days);
        return result;
    }
    
    // Loop to create the array of date objects for the next 6 days
    for (let i = 0; i < 7; i++) {
        let nextDate = addDays(date, i);
        let dateDetails = nextDate.toLocaleDateString('en-US', options).split(' ');
        dataslot.push({
            day: dateDetails[0], // 'Wednesday',
            date: dateDetails[1]  // '29'
        });
    }
    console.log(dataslot)