-1

I'm working on a node/express/mongo application and have an issue with Javascript's date objects.

var myDate = new Date(2017, 11, 5, 8, 30, 00, 00);
console.log(myDate)

It appears it's setting the time to 4:30 pm instead of 8:30 am. I've tried every variation of this. What's going on here? Any help appreciated, thanks

Rob
  • 14,746
  • 28
  • 47
  • 65
  • 2
    timezones, they are confusing (see the `Z` at the end of the string, that means ZULU = UTC = GMT - – Jaromanda X Dec 04 '17 at 03:11
  • If you need to construct a UTC date, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC – Phil Dec 04 '17 at 03:14
  • @JaromandaX Technically, UTC != GMT. For most cases, it doesn't matter though. – jhpratt Dec 04 '17 at 03:15
  • Possible duplicate of [How do you create a JavaScript Date object with a set timezone without using a string representation](https://stackoverflow.com/questions/439630/how-do-you-create-a-javascript-date-object-with-a-set-timezone-without-using-a-s) – jhpratt Dec 04 '17 at 03:15
  • 1
    @jhpratt - only mentioned GMT in case "ZULU" and "UTC" were unfamiliar to the OP :p having said that, the date/time in UTC and GMT are identical – Jaromanda X Dec 04 '17 at 03:16

1 Answers1

0

The Time portion of the Date object is always in UTC, if you want to offset you need to calculate it:

var now = new Date();

var myDate = new Date(2017, 11, 5, 8, 30 - now.getTimezoneOffset(), 0, 0);
console.log(myDate)  // 2017-12-06T08:30:00.000Z

Note: days are numbered months: 0-11!

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • The timezone offset is expressed in minutes and may not be evenly divisible by 60 since some offsets are at 30 or even 15 minute resolution. So for a place with an offset of 0530 (i.e. 330 minutes) the above will truncate the 30 minutes. Why not apply the offset to the minutes? `new Date(2017, 11, 5, 8, 30-now.getTimezoneOffset(), 0, 0)` will set the internal time value to the current timezone. Not sure what you mean by "*days are numbered from 0-6*"; in a date, the day number is from 1 to 28,29,30 or 31 depending on the length of the month. – RobG Dec 05 '17 at 06:45
  • @RobG you're right (in both points), thanks for helping improve the answer! – Nir Alfasi Dec 05 '17 at 07:26