开发者

How to display local time of the browser in a web app

I am writing a web app and I would like to display timestamps on the page in the user's localtime. There seems to be several ways to do this but it is not obvious what is a good way.

  1. Use geolocation from the IP address to get the timezone - This seems like a lot of overhead.
  2. Use javascript to finally render the datetime on the page - This seems like a lot of complex client side javascript.
  3. Use javascript to get the timezone and locale from开发者_运维百科 the user's preferences and save it in a cookie. The server can then use this to format the date. Server side code is nice, but there don't seem to be many good ways to get this for the first page load.
  4. Any options for http request headers? Which ones? How reliable across browsers are they?

Any advice on good ways to implement this?


Try my timeago jquery plugin. It converts UTC timestamps into fuzzy time phrases (e.g. "about 2 hours ago").

You output HTML like this:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

and the plugin turns that into something like this:

<abbr class="timeago" title="July 17, 2008">about a year ago</abbr>

by using a little jQuery like this:

jQuery(document).ready(function() {
  jQuery('abbr.timeago').timeago();
});


#2 is not very complex, you could even use something like http://ejohn.org/blog/javascript-pretty-date/ to display times like on this site ("2 hours ago").

If you absolutely against that, make a guess based on either JS time (seems less error-prone than guessing by IP) and let the user change it.


1) Yes, it's overhead. But you could get it once per session, and then store the offset.

2) Displaying the date with JavaScript isn't too complex. Look at the Date object.

I would make a guess at the user's timezone from his computer's local timezone (using JS), and then store that. I would also allow them to change the offset in their preferences of your web app.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜