-3

I am writing a tampermonkey script and the logic is as follows.

  1. make a GET request to fetch a certain value, and this will give me a date in the format '2021-05-01' This is date 1st May 2021.
  2. Now I get to the following dates within my javascript. 2 days before and after this date.
  3. so I want to calculate the following dates 29th April 2021, 30th April 2021, 2nd May 2021, 3rd May 2021. i.e. '2021-04-29','2021-04-30','2021-05-02','2021-05-03'

Please can someone help me write this.

My current code is as follows

//GET request to get a date value and save it to a variable called checkdate
var checkdate = GET-request. 

// add code to get 2 days plus and minus this date. 
var d = new Date(checkdate)
var x = 2
var newd = d.setDate(d.getDate() - x);
var dt = getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();

So when I run it for the date '2021-05-01', I end up with the following value for newd 1619654400000 and value for dt as 2021-04-29

so now I need to extract the date from this which should be '2021-04-29' and now I have to repeat this same code 4 times. Is there a better way to do this.

Vik G
  • 539
  • 3
  • 8
  • 22
  • 1
    Start with [*Converting a string to a date in JavaScript*](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript/5619588?r=SearchResults&s=3|118.4661#5619588) noting [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results), then see [*Add days to JavaScript Date*](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) (which also covers subtraction). When you've written some code, if you have issues post again. – RobG Mar 04 '21 at 22:38
  • @RobG I had added my code but messed up the saving. edited it now. – Vik G Mar 04 '21 at 23:01

1 Answers1

0

Date("2021-05-01").getTime() return the number of milliseconds and it should look like this 1619827200000 from here you can add or subtract the number of milliseconds for the needed dates like this.

let date_milliseconds= new Date(your_date_variable).getTime();
let one_day_millisec=1000*60*60*24;
let one_day_before= new Date(date_milliseconds-one_day_millisec);//If your date is 2021-05-01 this date should be 2021-04-30

Same goes for next day

Cristian GATU
  • 49
  • 1
  • 4
  • "2021-05-01" will be parsed as UTC, probably not what the OP expects, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Adding days by adding or subtracting milliseconds is not recommended as days aren't always 24 hours long where daylight saving is observed, see [*Add days to JavaScript Date*](https://stackoverflow.com/questions/563406/add-days-to-javascript-date). – RobG Mar 04 '21 at 23:26