-3
  1. Input Date in yyyymmdd (20180328) format.
  2. Get list of two previous months date (yyyymmdd).
  3. Output should be store in variable with format yyyymmdd so that I can use it later to run xyz in loop with all previous three months date.

Eg: If I enter 20170828 ,then it will return me 20170828 20170728 20170628 and I can use this outputs as input to xyz operation without calling xyz 3 separate times

JumpingJezza
  • 5,498
  • 11
  • 67
  • 106
  • What language are you using? – yaakov Mar 28 '18 at 22:24
  • @TricksfortheWeb javascript – Chiranjeev Singh Mar 28 '18 at 22:25
  • OK, hold on.... – yaakov Mar 28 '18 at 22:26
  • You're asking 3 questions, all are duplicates of very frequently asked questions that already have plenty of answers here. And you should show your attempt at answering the question, see [*How do I ask a good question?*](https://stackoverflow.com/help/how-to-ask) – RobG Mar 29 '18 at 09:03
  • 1
    Parsing: [*How to parse a string into a date object at JavaScript?*](https://stackoverflow.com/questions/5277170/how-to-parse-a-string-into-a-date-object-at-javascript). Add/subtract months: [*Javascript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date). Formatting: [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – RobG Mar 29 '18 at 09:09
  • @TricksfortheWeb Thanks.. I'm waiting :) – Chiranjeev Singh Mar 29 '18 at 17:45
  • @RobG , I've tried a lot using all previously asked question in this website and others too. I'm new to javascript and facing issue after implementing the solution mentioned in the forums that's why I've raised this question. Anyways Thanks for sharing above links. – Chiranjeev Singh Mar 29 '18 at 17:53
  • So use those links to perform the operations you want to perform. If you have difficulty with a particular part, post a question on that. You need to post what you've tried and where it's going wrong. – RobG Mar 30 '18 at 04:52

1 Answers1

0

OK, this should work:

let date = new Date();

let dt = {
  year: date.getFullYear(),
  month: date.getMonth() + 1,
  day: date.getDate()
};

meses = 1;

let printDate = dateX => {
  let d = {
    y: dateX.year,
    m: dateX.month < 10 ? "0" + dateX.month : dateX.month,
    d: dateX.day < 10 ? "0" + dateX.day : dateX.day
  };
  let p = document.createElement("p");
  p.innerHTML = d.y + d.m + d.d;
  document.body.appendChild(p);

  if(meses < 3){
    meses++;  
    printDate({year: dateX.year, month: +dateX.month-1, day: dateX.day});
  }
}

printDate(dt);

This is a bit dangerous because of the global variable there, but it does the job. https://jsfiddle.net/yak613/0kyL5L1e/

yaakov
  • 4,568
  • 4
  • 27
  • 51