[javascript] javascript toISOString() ignores timezone offset

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

This question is related to javascript datetime timezone-offset

The answer is


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.


moment.js FTW!!!

Just convert your date to a moment and manipulate it however you please:

var d = new Date(twDate);
var m = moment(d).format();
console.log(m);
// example output:
// 2016-01-08T00:00:00-06:00

http://momentjs.com/docs/


It will be very helpful to get current date and time.

var date=new Date();
  var today=new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().replace(/T/, ' ').replace(/\..+/, '');  

Using moment.js, you can use keepOffset parameter of toISOString:

toISOString(keepOffset?: boolean): string;

moment().toISOString(true)


This date function below achieves the desired effect without an additional script library. Basically it's just a simple date component concatenation in the right format, and augmenting of the Date object's prototype.

 Date.prototype.dateToISO8601String  = function() {
    var padDigits = function padDigits(number, digits) {
        return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
    }
    var offsetMinutes = this.getTimezoneOffset();
    var offsetHours = offsetMinutes / 60;
    var offset= "Z";    
    if (offsetHours < 0)
      offset = "-" + padDigits(offsetHours.replace("-","") + "00",4);
    else if (offsetHours > 0) 
      offset = "+" + padDigits(offsetHours  + "00", 4);

    return this.getFullYear() 
            + "-" + padDigits((this.getUTCMonth()+1),2) 
            + "-" + padDigits(this.getUTCDate(),2) 
            + "T" 
            + padDigits(this.getUTCHours(),2)
            + ":" + padDigits(this.getUTCMinutes(),2)
            + ":" + padDigits(this.getUTCSeconds(),2)
            + "." + padDigits(this.getUTCMilliseconds(),2)
            + offset;

}

Date.dateFromISO8601 = function(isoDateString) {
      var parts = isoDateString.match(/\d+/g);
      var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
      var isoDate = new Date(isoTime);
      return isoDate;       
}

function test() {
    var dIn = new Date();
    var isoDateString = dIn.dateToISO8601String();
    var dOut = Date.dateFromISO8601(isoDateString);
    var dInStr = dIn.toUTCString();
    var dOutStr = dOut.toUTCString();
    console.log("Dates are equal: " + (dInStr == dOutStr));
}

Usage:

var d = new Date();
console.log(d.dateToISO8601String());

Hopefully this helps someone else.

EDIT

Corrected UTC issue mentioned in comments, and credit to Alex for the dateFromISO8601 function.


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();

Moment js solution to this is

var d = new Date(new Date().setHours(0,0,0,0));
m.add(m.utcOffset(), 'm')
m.toDate().toISOString()
// output "2019-07-18T00:00:00.000Z"