如何从Javascript中的字符串中获取时区偏移量

Oma*_*aty 5 javascript timezone

我收到带有偏移量的字符串格式的日期,但javascript正在将其转换为本地设备时间

var d = new Date("2012-11-13T11:34:58-05:00");
debug.log(d);
Run Code Online (Sandbox Code Playgroud)

返回2012年11月13日星期二17:34:58 GMT + 0100(CET)

var offset = d.getTimezoneOffset();
debug.log(offset);
Run Code Online (Sandbox Code Playgroud)

返回-60(我的设备是utc + 1h)

我只想拥有偏移量的时间,或者在字符串中提到时区偏移量(示例中为-5h)

Oma*_*aty 1

我发现的唯一解决方案是通过解析字符串来创建自定义时间对象

//ex: 2012-11-13T10:56:58-05:00
function CustomDate(timeString){

    var completeDate = timeString.split("T")[0];
    var timeAndOffset = timeString.split("T")[1];
    //date
    this.year = completeDate.split("-")[0];
    this.month = completeDate.split("-")[1];
    this.day = completeDate.split("-")[2];

    this.date = this.year + "/" + this.month + "/"+this.day;

    //negative time offset
    if (timeAndOffset.search("-") != -1){
        var completeOffset = timeAndOffset.split("-")[1];
        this.offset = parseInt(completeOffset.split(":")[0]) * -1;

        var originalTime = timeAndOffset.split("-")[0];
        this.hours = parseInt(originalTime.split(":")[0]);
        this.minutes = parseInt(originalTime.split(":")[1]);
        this.seconds = parseInt(originalTime.split(":")[2]);

        this.time = this.hours + ":" + this.minutes + ":"+this.seconds;

    }
    ///positive time offset
    else if (timeAndOffset.search(/\+/) != -1){

        var completeOffset = timeAndOffset.split("+")[1];
        this.offset = parseInt(completeOffset.split(":")[0]);

        var originalTime = timeAndOffset.split("+")[0];
        this.hours = parseInt( originalTime.split(":")[0]);
        this.minutes = parseInt(originalTime.split(":")[1]);
        this.seconds = parseInt(originalTime.split(":")[2]);

        this.time = this.hours + ":" + this.minutes + ":"+this.seconds;
    }
    //no time offset declared
    else{
        this.hours = parseInt(timeAndOffset.split(":")[0]);
        this.minutes = parseInt(timeAndOffset.split(":")[1]);
        this.seconds = parseInt(timeAndOffset.split(":")[2]);
        this.offset = 0;

        this.time = this.hours + ":" + this.minutes + ":"+this.seconds;
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我想显示指定时区偏移量中接收到的时间 2012-11-13T11:34:58-05:00 :

var aDate = new CustomDate("2012-11-13T11:34:58-05:00");
alert("date: " + aDate.date +" time: "+aDate.time+" offset: "+aDate.offset);
Run Code Online (Sandbox Code Playgroud)

我得到

date: 2012/11/13 time: 11:34:58 offset: -5
Run Code Online (Sandbox Code Playgroud)

此解决方案的问题在于,日期和时间约定是在代码中手动定义的,因此它们不会自动适应用户的语言。