javascript toISOString() ignores timezone offset

Cyril Mestrom picture Cyril Mestrom · May 31, 2012 · Viewed 136.3k times · Source

I am trying to convert Twitter datetime to a local iso-string (for prettyDate) now for 2 days. I'm just not getting the local time right..

im using the following function:

function getLocalISOTime(twDate) {
    var d = new Date(twDate);
    var utcd = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(),
        d.getMinutes(), d.getSeconds(), d.getMilliseconds());

    // obtain local UTC offset and convert to msec
    localOffset = d.getTimezoneOffset() * 60000;
    var newdate = new Date(utcd + localOffset);
    return newdate.toISOString().replace(".000", "");
}

in newdate everything is ok but the toISOString() throws it back to the original time again... Can anybody help me get the local time in iso from the Twitterdate formatted as: Thu, 31 May 2012 08:33:41 +0000

Answer

user1936097 picture user1936097 · Jan 26, 2015

moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

The following works as well:

var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.