Search code examples
javascriptdatetimeunix-timestamp

JS Date incrementation


Doing this without libraries.

dates.forEach((date) => {
  if(date.getDay() == 6) {
    console.log('sat', date)
    var t = new Date()
    console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
  } else ...
}

Gives this output

sat 
Date Sat Jan 01 2022 00:00:00 GMT+0200 (Eastern European Standard Time)
sat new 
Date Sat Apr 02 2022 19:10:27 GMT+0300 (Eastern European Summer Time)

The point of this code is to see if a date is a saturday. If so, increment it towards becoming a work day (i know it says +1 but its a wip)

The result is that the day gets incremented. However for some reason it moves the date towards being in march. I have looked around and apparently this is how you're supposed to do it, but its not doing it.

When I try console.log('sat new', t.setDate(date.getDate() + 1)) (without new Date()) I get a timestamp of 1646236273249. Which this site converts to the 16th of March. Don't know how useful this is.

I hope I gave all the important information here.


Solution

  • var t = new Date() - not passing anything to the Date constructor will make it "right now". I think you need to pass the iterated date to the Date constructor:

    dates.forEach((date) => {
      if(date.getDay() == 6) {
        console.log('sat', date)
        var t = new Date(date) // this line
        console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
      }
    }