create javascript date UTC

38,242

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.

Share:
38,242

Related videos on Youtube

frenchie
Author by

frenchie

Started programming when I was 10. Never made it my profession but always programmed, mostly with Excel VBA for finance, and for some simple front-end web design in the early 2000's (ie. no jquery back then, what a pain it was with DHTML). One day, I get the idea of outsourcing the web development of my start-up: total cacacacacacacafukkkk! So: from VBA to C# .NET and Javascript in 5,000 pages of programming books, and lots of Stackoverflow! I think asking dumb questions is a smart way to learn. And as an internet entrepreneur, I've learned that what matters most is not knowing how to program but knowing what to program: discover the goyaPhone at www.goyaphone.eu

Updated on July 09, 2022

Comments

  • frenchie
    frenchie almost 2 years

    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.

  • Jake T.
    Jake T. about 7 years
    What is the functional difference between new Date( Date.UTC(2012, 10, 5) ); and Date.UTC(2012, 10, 5); ?
  • Sirko
    Sirko about 7 years
    @JakeT. Date.UTC() just returns the timestamp (a number). new Date( Date.UTC() ) will return a Date object.
  • JamesB
    JamesB over 4 years
    This doesn't answer the question. The author wants a Date object, moment.utc does not return a Date.
  • Josh Bowling
    Josh Bowling over 3 years
    I run TheDate.getTimezoneOffset();. I don't get 0 as I would expect, any idea how to resolve this?
  • RobG
    RobG over 2 years
    @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.