ISO 8601 Formatting of Dates with Timezone Offset in JavaScript
Goal: Construct a URL with a timestamp in ISO 8601 format that includes the timezone offset.
Approach:
Implementation:
The following JavaScript function constructs the ISO 8601 timestamp:
function toIsoString(date) { var tzo = -date.getTimezoneOffset(), // Negative offset means UTC is ahead of local time dif = tzo >= 0 ? '+' : '-', pad = function(num) { return (num < 10 ? '0' : '') + num; }; return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + 'T' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()) + dif + pad(Math.floor(Math.abs(tzo) / 60)) + ':' + pad(Math.abs(tzo) % 60); }
For example, if the local time is 2013/07/02 9am and the timezone offset is -7 hours (UTC is 7 hours ahead):
var dt = new Date(); console.log(toIsoString(dt)); // Outputs: "2013-07-02T09:00:00-07:00"
Note that the or - sign indicates whether the local time is ahead of or behind UTC.
The above is the detailed content of How to Generate ISO 8601 Timestamps with Timezone Offset in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!