0

simple problem:

When I try this on console:

new Date('2018', '01', '08')

I get this output

Date 2018-02-07T13:00:00.000Z

How to get it to the date I just set? like 2018-01-08T00:00:00?

Thanks a lot

Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70
  • As mentioned in Christian's answer, month is zero-based. Other than that, it actually is showing the date that you requested, it's just showing it in UTC time. For more information on the Javascript date object, I recommend this excellent post in an older question https://stackoverflow.com/a/15171030/3415209 – Daniel Bernsons Jan 08 '18 at 06:18
  • I see the post, but I cant convert into a specific timezone.. it has to be the user visiting. so it should just show output the system time – Raheel Hasan Jan 08 '18 at 06:22
  • @RaheelHasan try using moment.js for your datetime object. It is an excellent library for such kind of manipulations – Varun Sharma Jan 08 '18 at 06:23
  • @RasheelHasan I understand, I was just trying to point you in the direction of some background on how the Date object works. I'm guessing you're in a timezone similar to Sydney, Australia - +11 UTC. `2018-01-07T13:00:00.000Z` is exactly the same as `2018-01-08T00:00:00.000` in the UTC+11 timezone. – Daniel Bernsons Jan 08 '18 at 06:32

2 Answers2

4

The month parameter in the Date constructor is 0-based, meaning the months start from 0, not 1.

To get January as your date, you need to set month to 0:

new Date('2018', '0', '08')

For UTC, you can use Date.UTC to specify that the year, month and day are in UTC:

new Date(Date.UTC("2018", "0", "1"))
Christian Santos
  • 5,386
  • 1
  • 18
  • 24
2

Apart from the answer above by Christian, you can do the following to get current local time:

new Date(new Date()+'utc');
Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70