javascript toISOString() ignores timezone offset [duplicate]
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
Solution 1:
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);
console.log(localISOTime) // => '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.
Solution 2:
My solution without using moment
is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()
var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();