
Timezone Conversion in JavaScript: Why getTimezoneOffset() Will Betray You
Ask any JavaScript developer how to convert between timezones and someone will say: "use getTimezoneOffset() ." Don't. Here's why, and what to use instead. What getTimezoneOffset() Actually Returns const d = new Date (); console . log ( d . getTimezoneOffset ()); // e.g., -330 for IST, 300 for US/Eastern Two problems with this: 1. It returns the local timezone offset, not an arbitrary one. getTimezoneOffset() tells you the offset of the machine running the code. You cannot use it to find out what time it is in Tokyo from a server running in UTC. 2. The sign is backwards from what you'd expect. UTC+5:30 (India) returns -330 . UTC-5:00 (US East) returns 300 . The value is UTC - local , not local - UTC . This trips up almost everyone the first time. The Wrong Way to Convert Timezones // ❌ This only works if the server happens to be in the right timezone function toNewYorkTime ( utcDate ) { const offset = - 300 ; // "NYC is UTC-5" hardcoded const localTime = new Date ( utcDate . getTime ()
Continue reading on Dev.to Webdev
Opens in a new tab

