skip to Main Content

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 ?

3

Answers


  1. The post given by jonrsharpe provides the idea on how to acheive your requirement. To be more specific, refer the code below.

    const getNextSixDays = () => {
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const dateArray = [];
    
        for (let i = 0; i < 7; i++) {
            const date = new Date();
            date.setDate(date.getDate() + i);
            const day = days[date.getDay()];
            const dateInTwoDigit = String(date.getDate()).padStart(2, '0');
            dateArray.push({ day: day, date: dateInTwoDigit });
        }
    
        return dateArray;
    }
    
    console.log(getNextSixDays());
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
  3. You don’t want to create new Date object for each iteration. Checkout this

    let date_slots = [];
    let option = {
        weekday: 'long',
        day: '2-digit'
    };
    const date_object = new Date(); // single date object
    
    for (let i = 0; i < 7; i++) {
      if(i != 0) date_object.setDate(date_object.getDate() + 1);
      
      let [day,date] = date_object.toLocaleDateString('en-in', option).split(' ');
      date_slots.push({
        day,
        date
      })
    }
    
    console.log(date_slots)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search