25

Let's say I type the following code in the console:

var TheDate = new Date(2012, 10, 5);
TheDate.toUTCString();
"Sun, 04 Nov 2012 23:00:00 GMT" (I'm +1 hour ahead of GMT)

The result is that the date is actually set to the local time. How do I create a Date that's set to UTC? If I do TheDate.toUTCString() I want it to say 05 Nov 2012 00:00:00 GMT.

Thanks.

eerFun
  • 145
  • 8
frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

57

Use the Date.UTC() method:

var TheDate = new Date( Date.UTC(2012, 10, 5) );
console.log( TheDate.toUTCString() );

returns

Mon, 05 Nov 2012 00:00:00 GMT

Date.UTC

Accepts the same parameters as the longest form of the constructor, and returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time.

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • What is the functional difference between `new Date( Date.UTC(2012, 10, 5) );` and `Date.UTC(2012, 10, 5);` ? – Jake T. Apr 07 '17 at 17:38
  • 2
    @JakeT. `Date.UTC()` just returns the timestamp (a number). `new Date( Date.UTC() )` will return a `Date` object. – Sirko Apr 07 '17 at 20:06
  • I run `TheDate.getTimezoneOffset();`. I don't get `0` as I would expect, any idea how to resolve this? – Josh Bowling Sep 27 '20 at 17:46
  • @JoshBowling—a Date object doesn't have an offset, they're UTC. *getTimezoneOffset* returns the offset for the host system for the moment in time represented by the Date. Change system settings to a timezone with a different offset and *getTimezoneOffset* will return a different value. – RobG Jan 12 '22 at 03:36
2

I found a shorthand for it, You could also create your date in ISO format as new Date('YYYY-MM-DD') to create date as UTC:

var DateA = new Date( '2012-11-05' );
console.log( DateA.toUTCString() );

// note the difference between input methods

var DateB = new Date( Date.UTC(2012, 10, 5) );
console.log( DateB.toUTCString() );
eerFun
  • 145
  • 8
-4

I would suggest you use momentjs (

momentjs.com

), then all you have to do is:

var theDate = new Date(2012, 10, 5),
    utcDate = moment.utc(theDate);
Eudis Duran
  • 742
  • 3
  • 16
  • 3
    This doesn't answer the question. The author wants a Date object, moment.utc does not return a Date. – JamesB Sep 06 '19 at 23:14