javascriptjquerytimezonetimezone-offset

Get timezone offset from timezone name using Javascript


I found many solution that gives Timezone name from offset value. But I have Timezone name and I want offset value for that. I tried setTimezone('Asia/Kolkata'), but I think their is no method like setTimezone.

example:

Asia/Kolkata should give me -330 ( offset )

Solution

  • This has got the be the easiest way to accomplish this task with modern JavaScript.

    Note: Keep in mind that the offset is dependent on whether Daylight Savings Time (DST) is active.

    /* @return A timezone offset in minutes */
    const getOffset = (timeZone = 'UTC', date = new Date()) => {
      const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
      const tzDate = new Date(date.toLocaleString('en-US', { timeZone }));
      return (tzDate.getTime() - utcDate.getTime()) / 6e4;
    }
    
    console.log(`No arguments: ${getOffset()}`); // 0
    
    {
      console.log('! Test Case #1 >> Now');
      console.log(`Asia/Colombo     : ${getOffset('Asia/Colombo')}`);     //  330
      console.log(`America/New_York : ${getOffset('America/New_York')}`); // -240
    }
    
    {
      console.log('! Test Case #2 >> DST : off');
      const date = new Date(2021, 0, 1);
      console.log(`Asia/Colombo     : ${getOffset('Asia/Colombo', date)}`);     //  330
      console.log(`America/New_York : ${getOffset('America/New_York', date)}`); // -300
    }
    
    {
      console.log('! Test Case #3 >> DST : on');
      const date = new Date(2021, 5, 1);
      console.log(`Asia/Colombo     : ${getOffset('Asia/Colombo', date)}`);     //  330
      console.log(`America/New_York : ${getOffset('America/New_York', date)}`); // -240
    }
    .as-console-wrapper { top: 0; max-height: 100% !important; }