2

I have two date object like new Date(2019, 11, 1) and new Date("2019-12-01"). The obtained Date object values are different.

enter image description here

How can I get the same Date object for both values by any possible workarounds? I have tried by adding new Date().getTimezoneOffset(), but it did not work proper if I have new Date(2019, 11, 1, 4)

  • You can add time to your date string: `new Date("2019-12-01 00:00:00")` – Nick Parsons Nov 05 '19 at 09:58
  • Any workaround? So how about simply `new Date("2019-12-01 00:00:00")` and `new Date(2019, 11, 1, 0, 0, 0)`? ;) – Sebastian Kaczmarek Nov 05 '19 at 09:58
  • My case is I am giving the date in either new Date(2019, 11, 1) or new Date("2019-12-01") this format only. So, I can't change the initial values. – Kesavan Subramaniam Che Nov 05 '19 at 10:02
  • I would say the best option is to parse the string before passing it to the new date object. For example: const parsedDate = "2019-12-01".split("-"); And then initialize the date as follows: new Date(parsedDate[0], parsedDate[1]-1, parsedDate[2]); Or even better, use [Date.UTC](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) to initialize all your dates [new Date(Date.UTC(2019, 10, 9)]. – CJNaude Nov 05 '19 at 12:21

1 Answers1

0

In your first example, javascript is assuming the local timezone. For representing just-a-date, this is very problematic. Use instead Date.UTC(2019,11,1)

In the second example, javascript is assuming UTC which is what you want.

Much more details here.

bbsimonbb
  • 27,056
  • 15
  • 80
  • 110