Introduction
In this lab, we will learn how to convert a date into the extended ISO format (ISO 8601), including timezone offset. We will use the Date.prototype.getTimezoneOffset() method to get the timezone offset and reverse it. Then, we will define a helper function to normalize any passed number to an integer and pad it to 2 digits using String.prototype.padStart(). Finally, we will use the built-in methods in the Date prototype to build the ISO 8601 string with timezone offset. By the end of this lab, you will have a better understanding of how to manipulate dates in JavaScript.
Converting Dates to ISO Format with Timezone
To convert a date to the extended ISO format (ISO 8601), including the timezone offset, follow these steps:
- Open the Terminal/SSH and enter
nodeto begin coding. - Use
Date.prototype.getTimezoneOffset()to get the timezone offset and reverse it. Store its sign indiff. - Define a helper function,
pad(), that normalizes any passed number to an integer usingMath.floor()andMath.abs()and pads it to2digits, usingString.prototype.padStart(). - Use
pad()and the built-in methods in theDateprototype to build the ISO 8601 string with timezone offset.
Here's the code you can use:
const toISOStringWithTimezone = (date) => {
const tzOffset = -date.getTimezoneOffset();
const diff = tzOffset >= 0 ? "+" : "-";
const pad = (n) => `${Math.floor(Math.abs(n))}`.padStart(2, "0");
return (
date.getFullYear() +
"-" +
pad(date.getMonth() + 1) +
"-" +
pad(date.getDate()) +
"T" +
pad(date.getHours()) +
":" +
pad(date.getMinutes()) +
":" +
pad(date.getSeconds()) +
diff +
pad(tzOffset / 60) +
":" +
pad(tzOffset % 60)
);
};
Use the function toISOStringWithTimezone() with a new Date() object as the argument to get the date in ISO format with timezone offset. For example:
toISOStringWithTimezone(new Date()); // '2020-10-06T20:43:33-04:00'
Summary
Congratulations! You have completed the Date to ISO Format With Timezone lab. You can practice more labs in LabEx to improve your skills.