skip to Main Content

I have a date in this format – 20230926 (yyyymmdd).

whatever date I get at runtime I want to have dates till next 120 days in an array. For example If I get date 20230926. Then my final array should contain date from today till next 120 days. Means final array will have 120 records.

  finalArray = [26-09-2023,27-09-2023,28-09-2023.
   
    .etc till next 120 days]

. How can I do that?

2

Answers


  1. You can use a for-loop to iterate through a date object. For each step, increment the date by 1.

    const now = new Date();
    const daysInFuture = 120;
    const dates = getDatesInRange(now, daysInFuture);
    const expectedEndDate = getFutureDate(now, daysInFuture - 1); // Exclusive
    
    console.log(expectedEndDate.toString() === dates[dates.length - 1].toString());
    console.log(dates.length === 120);
    console.log(dates); // Show all the dates
    
    function getDatesInRange(startDate, count) {
      const results = [], currDate = new Date(startDate.getTime());
      for (let i = 0; i < count; i++) {
        results.push(new Date(currDate.getTime()));
        currDate.setDate(currDate.getDate() + 1);
      }
      return results;
    }
    
    function getFutureDate(relativeDate, days) {
      const result = new Date(relativeDate.getTime());
      result.setDate(result.getDate() + days);
      return result;
    }
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
  2. You can use getDate() to get the current date and increment days and set using setDate(). You have to do it upto 120 times to reach your limit.

    To deal with Local time,

    const currentDate = new Date();
    const nextDates = [];
    const dateLimit = 120;
    
    for(let i = 1; i <= dateLimit; i++){
      const tempDate = new Date();
      tempDate.setDate(tempDate.getDate() + i);
      nextDates.push(tempDate);
    }
    
    console.log(nextDates)

    For UTC operations, Use

    tempDate.setUTCDate(tempDate.getUTCDate() + i);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search