javascript toISOString() 忽略时区偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10830357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:06:21  来源:igfitidea点击:

javascript toISOString() ignores timezone offset

javascriptdatetimetimezone-offset

提问by Cyril Mestrom

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..

我正在尝试将 Twitter 日期时间转换为本地 iso 字符串(对于prettyDate),为期 2 天。我只是没有得到正确的当地时间..

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

在 newdate 中一切正常,但 toISOString() 再次将其扔回原来的时间...谁能帮我从 Twitterdate 中获取 ISO 中的当地时间,格式为:2012 年 5 月 31 日星期四 08:33:41 +0000

回答by user1936097

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

moment.js很棒,但有时您不想为简单的事情拉大量依赖项。

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 Zwhich represents Zulu timezone and can be replaced by your own.

slice(0, -1)摆脱了拖尾的Z代表祖鲁时区,可以通过自己的所取代。

回答by Dustin Silk

My solution without using momentis to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()

我不使用的解决方案moment是将其转换为时间戳,添加时区偏移量,然后转换回日期对象,然后运行toISOString()

var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();

回答by boxes

moment.js FTW!!!

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/

http://momentjs.com/docs/

回答by James

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 对象的原型。

 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 Alexfor the dateFromISO8601function.

更正了评论中提到的 UTC 问题,并将该功能归功于AlexdateFromISO8601

回答by Omer Gurarslan

Using moment.js, you can use keepOffsetparameter of toISOString:

使用moment.js,您可以使用 的keepOffset参数toISOString

toISOString(keepOffset?: boolean): string;

toISOString(keepOffset?: boolean): string;

moment().toISOString(true)

moment().toISOString(true)

回答by Nagnath Mungade

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(/\..+/, '');  

回答by Ravi Kumar Mistry

Moment js solution to this is

对此的时刻js解决方案是

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"