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

The below should work properly, and for all browsers (thanks to @MattJohnson for the tip)

_x000D_
_x000D_
Date.prototype.toIsoString = function() {_x000D_
    var tzo = -this.getTimezoneOffset(),_x000D_
        dif = tzo >= 0 ? '+' : '-',_x000D_
        pad = function(num) {_x000D_
            var norm = Math.floor(Math.abs(num));_x000D_
            return (norm < 10 ? '0' : '') + norm;_x000D_
        };_x000D_
    return this.getFullYear() +_x000D_
        '-' + pad(this.getMonth() + 1) +_x000D_
        '-' + pad(this.getDate()) +_x000D_
        'T' + pad(this.getHours()) +_x000D_
        ':' + pad(this.getMinutes()) +_x000D_
        ':' + pad(this.getSeconds()) +_x000D_
        dif + pad(tzo / 60) +_x000D_
        ':' + pad(tzo % 60);_x000D_
}_x000D_
_x000D_
var dt = new Date();_x000D_
console.log(dt.toIsoString());
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

Examples related to date-formatting

How to insert date values into table How do I format a date as ISO 8601 in moment.js? Java Convert GMT/UTC to Local time doesn't work as expected Compare two date formats in javascript/jquery How to ISO 8601 format a Date with Timezone Offset in JavaScript? What are the "standard unambiguous date" formats for string-to-date conversion in R? How to convert date in to yyyy-MM-dd Format? Convert timestamp to date in MySQL query Date formatting in WPF datagrid Return date as ddmmyyyy in SQL Server