Home > database >  How to format array of date
How to format array of date

Time:02-13

I am getting an array of dates in this format

Sat Feb 12 2022 01:00:00 GMT 0100 (West Africa Standard Time),Sun Feb 13 2022 01:00:00 GMT 0100 (West Africa Standard Time),Mon Feb 14 2022 01:00:00 GMT 0100 (West Africa Standard Time)

But i want it in a format like this

Sat, Feb 12, 2022,
Sun, Feb 13, 2022,
Mon, Feb 14, 2022

This is the code that output my date

function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    currentDate.setUTCDate(currentDate.getUTCDate()   steps);
  }

  return dateArray;
}
var currD = new Date().toISOString().slice(0,10);

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate()   days);
  return result;
}
 const futureDate = addDays(currD, 3);

const dates = dateRange(currD, futureDate);
console.log(dates);
alert(dates)

CodePudding user response:

Try this

const dates = [
    'Sat Feb 12 2022 01:00:00 GMT 0100 (West Africa Standard Time)',
    'Sun Feb 13 2022 01:00:00 GMT 0100 (West Africa Standard Time)',
    'Mon Feb 14 2022 01:00:00 GMT 0100 (West Africa Standard Time)',
];

const formatted = dates.map((date) => new Date(date).toDateString());

console.log(formatted);

  • Related