toISOStringWithTimezone
Converts a date to extended ISO format (ISO 8601), including timezone offset.
- Use
Date.prototype.getTimezoneOffset()to get the timezone offset and reverse it, storing 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.
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);
};