0

get the last three-month start date dynamically from the new date including the current month start date and pushed into an array expected output will be [new Date('09-01-2019'), new Date('08-01-2019'), new Date('07-01-2019'), new Date('06-01-2019')] my date formate is MM-DD-YYYY Is this possible in javascript?

Tej
  • 86
  • 5
  • 2
    yes, it is possible, but, what problem are you facing to achieve it? What have you tried? – Calvin Nunes Sep 17 '19 at 12:59
  • @CalvinNunes thanks for the reply I tried with this code `const newDate = new Date("09-01-2019"); const dateArr = []; newDate.setMonth(newDate.getMonth() - 4); dateArr.push(newDate.toLocaleDateString());` i am getting the fourth month start date only, –  Sep 17 '19 at 13:10
  • Add your try inside your question, not as comment, use the [edit] – Calvin Nunes Sep 17 '19 at 13:11
  • For me, `new Date('09-01-2019')` returns an invalid date. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Sep 18 '19 at 05:06

2 Answers2

0

Try this:

let d = new Date();
d.setDate(1);
let dteList = [new Date(d.setMonth(d.getMonth())), new Date(d.setMonth(d.getMonth() - 1)), new Date(d.setMonth(d.getMonth() - 1)), new Date(d.setMonth(d.getMonth() - 1))]
console.log(dteList);
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
0

new Date('09-01-2019') returns a Date object. In some implementations, it will represent an invalid date.

If you want an array of Date objects, best to call the Date constructor with the values rather than building a string and using the built–in parser. It may also be useful to have a function that takes optional parameters for the number of dates to return and a start date, e.g.

// Return array of n dates from the start date
function getLastNMonths(n = 0, d = new Date()) {
  let y = d.getFullYear(),
      m = d.getMonth(),
      dates = [];

  do {
    dates.push(new Date(y, m--, 1));
  } while (n--);

  return dates;
}

console.log('Current month:');
getLastNMonths().forEach(d => console.log(d.toString()));

console.log('Current plus prior 6 months:');
getLastNMonths(6).forEach(d => console.log(d.toString()));

console.log('1 Jan 2000 plus prior 3 months:');
getLastNMonths(3, new Date(2000,0,1)).forEach(d => console.log(d.toString()));
RobG
  • 142,382
  • 31
  • 172
  • 209