How to display the time in the user's time zone?

On my site, the only place I use time is when I insert it into the database. When I pulled it out, I would like to display the time according to the user's time zone. I create this part of the page in C # (maintained by ASP.NET but not using .aspx code files).

How to display the time in accordance with the user's time zone? Do I have the feeling that I need the user to enter their location before I can do this? What is the best way to get time from a place and save daylight? or trick by translating UTC to it via JS and jquery?

+4
source share
3 answers

You can use the Date Javascript object to get it. Date.getTimezoneOffset () will give you the difference in minutes between local and UTC date representations. The actual value is ultimately derived from the system clock, which, if installed correctly, will know which time zone it is in.

+6
source
  • You can either ask the user to select the time zone as you suggested.

  • You can use (new Date).getTimezoneOffset(); as suggested in Robusto's answer . This will return the number of minutes to subtract from the user's local time to get UTC. The user must set the correct time zone in the operating system to give good results.

  • One more trick to β€œguess” the user's time zone by performing client-side date comparisons in JavaScript between new Date(); and the timestamp generated by the server.

    The advantage of this is that it will work even if the user did not configure the correct regional settings in the operating system. If the user's computer clock is accurate to +/- 30 minutes, they must be reliable.

+3
source

Just pass the UTC time to the JavaScript Date() constructor. The resulting Date object will be the time in the user local time zone based on their computer settings.

 var gmt = new Date('Feb, 19 2010 13:00:00 GMT'); alert(gmt); 

In Chrome, the Pacific Standard Time Zone displays

  Fri Feb 19 2010 05:00:00 GMT-0800 (Pacific Standard Time) 

If you need this information on the server side, do not worry when asking the user for your location. Just ask them directly about the time zone. Many sites (especially forums) already do this.

+1
source

Source: https://habr.com/ru/post/1301867/


All Articles