The getTimeZoneOffset() method
Syntax of the getTimeZoneOffset() method
The syntax is given as:
- dateObj: A date variable on which the getTimeZoneOffset() method is applied
- varrOffset: A variable in which the return value is stored
The timezone offset of the user’s local solar time against the Coordinated Universal Time in minutes.
Even though the getTimeZoneOffset() method is applied only on a date variable, the value of the date variable has nothing to do with the return value of this method. The output of the getTimeZoneOffset() is a NaN only when the date variables are given a wrong value to be initialized upon.
Example 1: Fetching the timezone with a date variable
For this, simply create a new Date variable using the following line of code:
No arguments have been given to the constructor of the Date object
Afterward, simply apply the getTimeZoneOffset() method and store the result in a new variable named as offsetVar as:
Pass this offsetVar to the console log function to display the output on to the terminal:
Execute the program, and the outcome on the terminal will be:
The timezone offset is -300.
Example 2: Passing Values in the Date constructor
This time around, create two different date variables as dateVar1 and dateVar2. For one of these, pass a valid date string inside the Date() constructor, and for the second one, pass an invalid Date string inside the Date() constructor:
var dateVar2 = new Date("45 2 2020");
The second date variable has been initialized on an invalid value in the constructor. Now, apply the getTimeZoneOffset() and wrap them in a console log function to get the output straight to the terminal:
"The timezone offset using dateVar1 : ",
"The timezone offset using dateVar2 : ",
After that, execute the program and observe the output to be:
Two things are evident from the output screenshot above:
- The value inside the date constructor doesn’t affect the timezone offset as long as it is valid.
- If the value passed to the Date constructor is invalid, getTImeZoneOffset() will return the timezone offset as NaN.
That’s it for this article.