Post 2022-03
How to obtain global time and build the world clock
Today I want to show how to obtain the global time (Greenwich Mean Time) and how to set up the time for world clock. You can see the effect by clicking the figure blow. Thanks for the post from "楼教主".
- getTimezoneOffset( ) returns the shifted time S between the current time C and GMT: S = GMT - C.
- For example, if we are in EST time zone, our time is GMT-0400, we should add 4*60 =240 mins to EST in order to obtain GMT.
- GMT = current time + getTimezoneOffset( ).
- If we are in New York (GMT -0400), we can set the time below: EST = GMT - 4 hours.
- If we are in Beijing (GMT +0800), we can set the time below: Beijing Time = GMT + 8 hours.
Here are the sample codes:
-
var dt = new Date; console.log( dt.getTimezoneOffset() ); // -480
-
The final codes are shown below and you can see the effect here or click the figure on the top right.
var dt = new Date; console.log( dt.getTimezoneOffset() ); // -480 var dt = new Date; dt.setMinutes( dt.getMinutes() + dt.getTimezoneOffset() ); // current time(mins) + time zone shift(mins) var dt_hour = 3; var dt_min = 0; function iniTime() { var now = new Date(); mincr = dt.getMinutes() + dt_min; hincr = dt.getHours() + dt_hour; console.log( "GMT format: ", now.toLocaleString()); console.log( "Local time format: ", now); } iniTime();
For more information, please refer to javascript obtaining global time.
View More Blogs