Home >Web Front-end >JS Tutorial >How to Format a JavaScript Date in ISO 8601 with Timezone Offset?
ISO 8601 Formatting of Date with Timezone Offset in JavaScript
This article addresses the common issue of how to format a JS date in the ISO 8601 format with an offset from UTC. It starts by discussing the goal of formatting the URL in the correct format, based on the W3C recommendation.
The solution involves a series of steps:
However, the question arises as to how to handle negative values for getTimezoneOffset(). The provided answer utilizes a helper function to address this:
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); }
This helper function takes a date as an argument and returns a properly formatted ISO 8601 string, including the timezone offset.
The above is the detailed content of How to Format a JavaScript Date in ISO 8601 with Timezone Offset?. For more information, please follow other related articles on the PHP Chinese website!