How to create a date with a set timezone without using a string representation?
For creating a date with a set timezone without using a string representation, Date Object method is used. More about this method can be learnt from here. It is a built in function in Javascript used to work with dates and times.
Syntax:
new Date(year, month, date, hour, minute, second, millisecond)
Approach 1:
Using this method, you can create a date with a set timezone. All you have to do is to use this inbuilt function by typing new Date() and then store the value in a new variable. Then display the contents of this variable using document.getElementById(“demo”).innerHTML.
Example 1:
<html> <body> <h2>GeeksforGeeks</h2> <p id= "demo" ></p> <script> var d = new Date(2019, 10, 4, 1, 43, 30, 0); document.getElementById( "demo" ).innerHTML = d; </script> </body> </html> |
Output:
Approach 2:
Using Date() method, a new date is created and that is stored in a variable. then using getTimezoneOffset() method we are able to add or subtract the timezone offset.
Example 2:
<html> <body> <h2>GeeksforGeeks</h2> <p id= "demo" ></p> <script> var d = new Date(2012, 9, 4); d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000); document.write(d); </script> </body> </html> |
Output: