JavaScript getTimezoneOffset(): Find the Difference Between UTC and Local Time

The JavaScript getTimezoneOffset() method is used when we need to find the difference between UTC (same as GMT) and local time. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let timeDifference = d.getTimezoneOffset();
      document.getElementById("xyz").innerHTML = timeDifference;
   </script>

</body>
</html>
Output

In the above example, the following JavaScript statement:

const d = new Date();

creates a new "Date" object with the "new Date()" constructor. This method generates a new date and time object using the current system clock time.

Then the following JavaScript statement:

let timeDifference = d.getTimezoneOffset();

calls the Date object's getTimezoneOffset() method to obtain the time zone offset in minutes between the user's local time zone and UTC. A negative value means the local time zone is behind UTC, while a positive value means it is ahead of UTC. The time zone offset value obtained is saved in the timeDifference variable.

Finally, the following JavaScript statement:

document.getElementById("xyz").innerHTML = timeDifference;
finds the HTML element with the id attribute "xyz" and sets its innerHTML property to the value stored in the timeDifference variable using the document.getElementById() method. The time zone offset will be displayed on the web page as a result of this.

JavaScript getTimezoneOffset() syntax

The syntax of the getTimezoneOffset() method in JavaScript is:

x.getTimezoneOffset()

where x must be an object of the Date() constructor.

The getTimezoneOffset() method returns a number, which will be the time difference between UTC and local time in minutes.

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

Advantages of the getTimezoneOffset() method in JavaScript

Disadvantages of the getTimezoneOffset() method in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!