How to ISO 8601 format a Date with Timezone Offset in JavaScript?

前端 未结 11 1686
时光说笑
时光说笑 2020-11-22 09:32

Goal: Find the local time and UTC time offset then construct the URL in following format.

Example URL: /Actions/Sleep?dura

11条回答
  •  礼貌的吻别
    2020-11-22 09:48

    You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

    Date.prototype.getISOTimezoneOffset = function () {
        const offset = this.getTimezoneOffset();
        return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
    }
    
    Date.prototype.toISOLocaleString = function () {
        return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
            this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
            this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
            this.getMilliseconds().leftPad(3);
    }
    
    Number.prototype.leftPad = function (size) {
        var s = String(this);
        while (s.length < (size || 2)) {
            s = "0" + s;
        }
        return s;
    }
    

    Example usage:

    var date = new Date();
    console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
    // Prints "2020-08-05T16:15:46.525+10:00"
    

    I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

    (The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

提交回复
热议问题