ISO 8601 Formatting Dates with Timezone Offset in JavaScript
To efficiently format dates with timezone offsets in ISO 8601 format, leverage the following guidelines:
W3C Recommendation:
Consider the example: "2002-10-10T12:00:00−05:00". This signifies noon on October 10, 2002, accounting for the Central Daylight Savings Time (as well as Eastern Standard Time within the U.S.). Its equivalence in UTC is "2002-10-10T17:00:00Z," a five-hour difference.
Formatting Steps:
Handling Negative Timezone Offsets:
When getTimezoneOffset() returns negative values, such as "-120," the format should adhere to the following: "2013-07-02T09:00:00 12:00".
Helper Function:
This handy function simplifies ISO 8601 date formatting:
function toIsoString(date) { var tzo = -date.getTimezoneOffset(), 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); } var dt = new Date(); console.log(toIsoString(dt));
The above is the detailed content of How to Format Dates with Timezone Offsets in ISO 8601 Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!