-2

this has been answered here however maybe something has changed as that no longer works.

function firstAndLast() {
  const startDate = new Date(2020, 8, 1);
  const endDate = new Date(2020, startDate.getMonth() + 1, 0)

  console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z
  console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z
}

firstAndLast();

as the docs say the parameters are new Date(YYYY, MM, DD, hh, mm, ss, ms)

I am entering the year 2020 the month august (note this is node not browser) and day 1 the first of the month. What is going on here?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ctfrancia
  • 1,248
  • 1
  • 15
  • 39
  • 2
    Your code has a syntax error, you can't repeat the `const` keyword like that. – Barmar Oct 21 '20 at 15:41
  • Does this answer your question? [Get first and last date of current month with JavaScript or jQuery](https://stackoverflow.com/questions/13571700/get-first-and-last-date-of-current-month-with-javascript-or-jquery) – Liam Oct 21 '20 at 15:43
  • 1
    Your comments and the actual output differ - looks like it's working? – chazsolo Oct 21 '20 at 15:43
  • @Liam that's what I linked to, and that's the code that is posted there. However, if you run the code snippet you'll see the dates are not correct. There are not 29 days in September – Ctfrancia Oct 21 '20 at 15:44
  • @chazsolo i get startDate "2020-08-31T22:00:00.000Z" endDate "2020-09-29T22:00:00.000Z" as outputs. there are not 29 days in September – Ctfrancia Oct 21 '20 at 15:45
  • It's converting to your local timezone, which subtracts a day – Barmar Oct 21 '20 at 15:47
  • 2
    It's subtracting 2 hours. – Barmar Oct 21 '20 at 15:47
  • @Barmar alright then it looks like I need to some how avoid this two hour subtraction. – Ctfrancia Oct 21 '20 at 15:51

1 Answers1

1

You have to consider the Timezone offset. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getTimezoneOffset

function firstAndLast() {
  const offset = new Date().getTimezoneOffset() / 60

  const startDate = new Date(2020, 8, 1, 0-offset);
  const endDate = new Date(2020, startDate.getMonth() + 1, 0, 0-offset)

  console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z
  console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z
}

firstAndLast();
Romain V...
  • 423
  • 2
  • 10
  • thanks! I was looking up the offset but was mucking about with it and couldn't really figure out how to do it exactly, but, this works great! Thanks! – Ctfrancia Oct 22 '20 at 09:04