0

如果我的 java web 应用程序部署在美国,无论客户所在的国家/地区如何,我都会获得美国时间。但是,如果客户在印度,他应该使用时区或区域设置或用户偏好来获取印度时间。我应该怎么办?

谁能帮助我。

4

2 回答 2

1

通过用户 IP 地址确定国家(使用一些网络服务或任何特殊的本地库)。如果是印度,则根据适当的时区显示时间。

于 2012-08-27T14:23:24.427 回答
0

在我之前的项目(一个由不同地区办公室的客户使用的 Web 应用程序)中,我们曾经依靠对象的getTimezoneOffset()值来找出客户的时区偏移量,维护到国家的偏移量地图和适当地显示区域。DateJavascript

例如

  • 330 -> IST
  • -240 -> 美国东部标准时间
  • -200 -> EST5EDT

ETC。,

timezoneoffset 曾经存储在客户端的 cookie 中,并用于服务器端的每个请求。如果未找到 cookie(当用户清除 cookie 时发生),我们使用了一个中间页面来确定时区偏移,设置 cookie 并将用户重定向到他打算访问的页面。

在客户端设置cookie(示例代码):

document.cookie= 
    "clientOffset=" + new Date()).getTimezoneOffset() 
    + "; expires=" + expireDate.toGMTString() 
    + "; domain=<your domain>;";

在服务器端,

// aRequest is of type HttpServletRequest
Cookie [] cookies = aRequest.getCookies();
if (null == cookies) {
    // redirect the user to the intermediate page that gets the client offset and 
    // takes the user the actually-intended page. 
    return;
}
for (Cookie cookie : cookies) {
    // Find the cookie whose name matches the one you are looking for and 
    // read the value and parse to an integer.
}

日期转换为用户的时区,如下所示:

// Here 'date' represents the date to be displayed in the server's time zone.
Date date = new Date();
SimpleDateFormat userDateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS z");
// As mentioned above, you would maintain a map of clientOffset to timezone ID
// Let's say your client is in EST time zone which means you will get -240 as the
// client offset.
userDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));

// This would convert the time in server's zone to EST.
System.out.println(userDateFormat.format(date));

希望这可以帮助!

于 2012-08-27T14:18:06.793 回答