Requirements: In order to improve user experience, the website should display the corresponding time according to the current user's time zone, obtain the current browser time zone information through js and pass it to the backend, and then display the processed data to the user. (Or the front-end data is converted)
JavaScript gets the time zone of the current client
The Intl object is a namespace for the ECMAScript internationalization API that provides precise string comparison, number formatting, and date formatting. We need to use this API's DateTimeFormat object.
For details, please refer to:The hyperlink login is visible.
Code:
You can see the output: Asia/Shanghai, which is my time zone is Shanghai.
UTC time zone offset
In order to better localize the display time, we can obtain the UTC time zone offset of the current browser, and increase or decrease the UTC time accordingly, which we can obtain through the getTimezoneOffset method of the Date object instance (note the returned resultThe unit is the cent):
Documentation:The hyperlink login is visible.
Chrome browser simulates different regions, outputs offset, console DevTools -> More Tools -> sensor, modifies the position, as shown below:
new Date() Wed Sep 20 2023 19:47:47 GMT+0800 (China Standard Time) new Date().getTimezoneOffset()
-480 new Date() Wed Sep 20 2023 13:48:12 GMT+0200 (Mitteleuropäische Sommerzeit) new Date().getTimezoneOffset()
-120 new Date() Wed Sep 20 2023 08:48:19 GMT-0300 (Horário Padrão de Brasília) new Date().getTimezoneOffset()
180 (End)
|