开发者

How do i display the time in the user time zone?

On my site the only place i use time is when i insert into the DB. When i pull it i would like to display the time according to the user time zone. I am generating this part of the page in C# (served in ASP.NET but not using .aspx code files).

How do i display the time according to the user time zone? I have a feeling i need to have the user input his location before i can d开发者_JS百科o this? Whats the best way to get time from location and take daylights saving into consideration? or cheat by translating UTC to his via JS and jquery?


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


  1. You can either ask the user to choose the timezone as you suggested.

  2. 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 have configured the correct timezone in the operating system for this give good results.

  3. Another trick to "guess" the user timezone by doing a client-side date comparison in JavaScript between new Date(); and a timestamp generated by the server.

    The advantage of this is that it would work even if the user would not have configured the correct regional settings in the operating system. As long as the computer clock of the user is accurate to +/- 30 minutes, it should be reliable.


Simply pass the UTC time to the JavaScript Date() constructor. The resulting Date object will be the time in the user's local timezone, based on their computer's settings.

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

In Chrome, in the Pacific timezone, this displays

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

If you need to have this information server-side, don't bother asking the user for their location. Just ask them for their timezone directly. Lots of sites (particularly forums) already do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜