Skip to content

Instantly share code, notes, and snippets.

@80xer
Created December 9, 2022 19:20
Show Gist options
  • Save 80xer/8542d06bd5b72612a1f9150f46aa37d4 to your computer and use it in GitHub Desktop.
Save 80xer/8542d06bd5b72612a1f9150f46aa37d4 to your computer and use it in GitHub Desktop.
convert to string from date object with timezone
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()); //'2022-11-23T17:03:19+09:00'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment