UTC Times in JavaScript

A lttle searching turned out you can do this:

var now = new Date(),
    utcDate = new Date(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(), 
        now.getUTCSeconds()
    );

Even shorter:

var utcDate = new Date(new Date().toUTCString().substr(0, 25));

How do you convert a JavaScript date to UTC?

It is a commonly used way, instead of creating a ISO8601 string, to get date and time of UTC out. Because if you use a string, then you'll not be able to use every single native methods of Date(), and some people might use regex for that, which is slower than native ways.

But if you are storing it in some kind of database like localstorage, a ISO8601 string is recommended because it can also save timezone offsets, but in your case every date is turned into UTC, so timezone really does not matter.


If you want the UTC time of a local date object, use the UTC methods to get it. All javascript date objects are local dates.

var date = new Date(); // date object in local timezone

If you want the UTC time, you can try the implementation dependent toUTCString method:

var UTCstring = date.toUTCString();

but I wouldn't trust that. If you want an ISO8601 string (which most databases want) in UTC time then:

var isoDate = date.getUTCFullYear() + '-' +
              addZ((date.getUTCMonth()) + 1) + '-' +
              addZ(date.getUTCDate()) + 'T' +
              addZ(date.getUTCHours()) + ':' +
              addZ(date.getUTCMinutes()) + ':' +
              addZ(date.getUTCSeconds()) + 'Z';

where the addZ function is:

function addZ(n) {
  return (n<10? '0' : '') + n;
}

Modify to suit.

Edit

To adjust a local date object to display the same time as UTC, just add the timezone offset:

function adjustToUTC(d) {
  d.setMinutes(d.getMinutes() + d.getTimezoneOffset()); 
  return d;
}

alert(adjustToUTC(new Date())); // shows UTC time but will display local offset

Take care with the above. If you are say UTC+5hrs, then it will return a date object 5 hours earlier but still show "UTC+5"

A function to convert a UTC ISO8601 string to a local date object:

function fromUTCISOString(s) {
  var b = s.split(/[-T:\.Z]/i);
  var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
  return n;
}

alert(fromUTCISOString('2012-05-21T14:32:12Z'));  // local time displayed

Tags:

Javascript