Date to ISO format with timezone

JavaScript, Date · Oct 13, 2021

Converts a date to extended ISO format (ISO 8601), including 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);
};
toISOStringWithTimezone(new Date()); // '2020-10-06T20:43:33-04:00'

More like this

  • Number of seconds to ISO format

    Returns the ISO format of the given number of seconds.

    JavaScript, Date · Oct 13, 2021

  • String is ISO formatted date

    Checks if the given string is valid in the simplified extended ISO format (ISO 8601).

    JavaScript, Date · Nov 29, 2020

  • Format duration

    Returns the human-readable format of the given number of milliseconds.

    JavaScript, Date · Oct 22, 2020