Javascript 在 JSF 中 - 获取客户端的语言环境(以浏览器的时区显示时间)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8600500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In JSF - Getting the Client's Locale (To Display time in browser's timezone)
提问by Ben
I'm writing a webapp in JSF 2.0 that displays Timestamps as part of the information to the user. I would like the user to see the timestamps localized to their location (browser's locale).
我正在用 JSF 2.0 编写一个 webapp,它向用户显示时间戳作为信息的一部分。我希望用户看到本地化到他们的位置(浏览器的语言环境)的时间戳。
So far, whatever I did, the timestamps would always appear localized to the timezone of the server.
到目前为止,无论我做什么,时间戳总是显示为本地化到服务器的时区。
I tried getting the locale with these methods:
我尝试使用以下方法获取语言环境:
Locale browserLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
or
或者
Locale browserLocale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
Both returned the server's locale.
两者都返回了服务器的语言环境。
I then use the locale object with SimpleDateFormat
to print timestamps.
然后我使用语言环境对象 withSimpleDateFormat
来打印时间戳。
Am I using the correct API?
I've read somewhere that you have to use client side code (Javascript) to get the browser's timezone. Is that correct? How would you do that?
我是否使用了正确的 API?
我在某处读到你必须使用客户端代码(Javascript)来获取浏览器的时区。那是对的吗?你会怎么做?
Thank's 'n' Advance.
谢谢'n'提前。
UPDATEfound this(jsTimezoneDetect) JavaScript code. But I'm still not sure how to translate the timezone to a Java Locale
Object
UPDATE发现了这个(jsTimezoneDetect) JavaScript 代码。但我仍然不确定如何将时区转换为 JavaLocale
对象
回答by Pawe? Dyda
You probably should use built-in formatting tag instead of SimpleDateFormat. Your question implies that you want to show date and time to International user, and in this case you should really use user's local format (they tend to differ, you know).
您可能应该使用内置格式标记而不是 SimpleDateFormat。您的问题意味着您想向国际用户显示日期和时间,在这种情况下,您应该真正使用用户的本地格式(您知道,它们往往会有所不同)。
In case of time zone, it has nothing to do with Internationalization and Localization, i.e. there are several different time zones in USA. There are two approaches you can use here:
在时区的情况下,它与国际化和本地化无关,即美国有几个不同的时区。您可以在此处使用两种方法:
Store time zone information in the user profile (if you have one). This is the easiest way and allow you to use built-in
<f:convertDateTime>
tag.Get time zone information from web browser. You can get it via Ajax request just like in Ben's example. Technically you can also use
<f:convertDateTime>
tag here.You can send the timestamps in UTC in some common, locale-independent (or invariant if you prefer) format, parse it on the client side to create JavaScript's date object and format for locale with Globalize.
将时区信息存储在用户配置文件中(如果您有的话)。这是最简单的方法,允许您使用内置
<f:convertDateTime>
标签。从网络浏览器获取时区信息。您可以像 Ben 的示例一样通过 Ajax 请求获取它。从技术上讲,您也可以
<f:convertDateTime>
在这里使用标签。您可以以某种常见的、与语言环境无关(或如果您喜欢不变)的格式发送 UTC 中的时间戳,在客户端解析它以使用Globalize为语言环境创建 JavaScript 的日期对象和格式。
Some examples will follow but let me explain something first.
下面会举一些例子,但让我先解释一下。
Locale browserLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
This willgive you web browser's locale (but not time zone, since this is notlocale related). It will actually read the contents of HTTP Accept-Language header and choose the best possible locale. If it is not working for you, please make sure that you have correctly set supported locales in your faces-config.xml
. By best possible Locale, I understand that it will try to use user's most preferred Locale (if that's supported by your application), then second best and so on. If none of the Locales is supported, it will fall-back to your application's default Locales (again, faces-config.xml
has to have this setting) or to server's default Locale if this setting is missing (or at least I think so, it kind of makes sense).
这将会给你的网页浏览器的语言环境(而不是时区,因为这是没有语言环境有关)。它实际上会读取 HTTP Accept-Language 标头的内容并选择最佳的语言环境。如果它不适合您,请确保您在faces-config.xml
. 通过最好的语言环境,我知道它将尝试使用用户最喜欢的语言环境(如果您的应用程序支持),然后是次佳的,依此类推。如果不支持任何语言环境,它将回退到您的应用程序的默认语言环境(同样,faces-config.xml
必须具有此设置)或如果缺少此设置(或至少我认为是这样,这有点有意义)或服务器的默认语言环境)。
Locale browserLocale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
This one will give you the top Locale from Accept-Language header. Please check your web browser's settings - there is almost no wayfor it to give you the server Locale, unless they are exactly the same as your web browser's. It can give you server's defaults if and only if, none of the web browser's Locale is supported by JVM (which seems a bit unlikely).
这将为您提供 Accept-Language 标题中的顶级语言环境。请检查您的网络浏览器的设置 - 它几乎无法为您提供服务器区域设置,除非它们与您的网络浏览器完全相同。当且仅当 JVM 不支持任何 Web 浏览器的 Locale(这似乎不太可能)时,它才能为您提供服务器的默认值。
BTW. FacesContext.getCurrentInstance().getExternalContext().getRequestLocales()
will give you the Iterator so you can manually iterate through the list of Locales in Accept-Language header. It is just to let you know, you probably should not use it (UIViewRoot is really enough).
顺便提一句。FacesContext.getCurrentInstance().getExternalContext().getRequestLocales()
将为您提供迭代器,以便您可以手动遍历 Accept-Language 标头中的区域设置列表。只是为了让您知道,您可能不应该使用它(UIViewRoot 真的足够了)。
Now, suppose you have some bean with the user profile and the method which will give you the time zone. This method is better than Ajax call, in the sense that it might happen that two different time zones have the same UTC offset but switch Daylight Saving Time on different date (in other words some timestamps would be printed incorrectly). Anyway, in case like this, you can format your time-stamp like this (date also come from some bean):
现在,假设您有一些带有用户配置文件的 bean 和可以为您提供时区的方法。这种方法比 Ajax 调用更好,因为可能发生两个不同的时区具有相同的 UTC 偏移量但在不同日期切换夏令时(换句话说,某些时间戳会被错误打印)。无论如何,在这种情况下,您可以像这样格式化时间戳(日期也来自某个 bean):
<h:outputText value="#{someBean.timestamp}">
<f:convertDateTime type="both" dateStyle="default" timeStyle="default" timeZone="#{userProfile.timeZone}" />
</h:outputtext>
Now let me explain the attributes:
现在让我解释一下属性:
- type - what to show, both means date and time
- dateStyle - style of date (out of short, medium, long, full, default). You should really use default here as this will use the most proper format for each Locale
- timeStyle - similar to date style but for time part
- timeZone - takes either an UTC offset (so you don't need to convert anything) or time zone name (i.e. America/Los_Angeles).
- type - 要显示的内容,都表示日期和时间
- dateStyle - 日期样式(短、中、长、完整、默认)。您真的应该在这里使用默认值,因为这将为每个区域设置使用最合适的格式
- timeStyle - 类似于日期样式,但用于时间部分
- timeZone - 采用 UTC 偏移量(因此您无需转换任何内容)或时区名称(即 America/Los_Angeles)。
The tag will use current view Locale by default, so you do not have to worry about this part, especially if you set up Locale support correctly.
标签默认会使用当前视图的 Locale,所以你不必担心这部分,特别是如果你正确设置了 Locale 支持。
Combining it with Ajax (see Ben's answer) would be easy enough (I think).
将它与 Ajax(见 Ben 的回答)结合起来很容易(我认为)。
I also mentioned that you can write out invariant dates, parse them on the client-side and then format them with Globalize. Assuming that you have parsed date already (it depends on the representation you want to use, so I will skip this part), it could be done like that:
我还提到你可以写出不变的日期,在客户端解析它们,然后用 Globalize 格式化它们。假设您已经解析了日期(这取决于您要使用的表示形式,因此我将跳过这一部分),可以这样做:
// you also have to assign the culture based on UIViewRoot locale and send it out with JavaScript
Globalize.culture(theLocale);
var formattedDateTime = Globalize.format(parsedDateTime, "f"); // this will use short date time format
Unlike Java, Globalize have only short ("f") and long ("F") date and time formats. So I decided on using short one.
Please also keep in mind, that Globalize cultures are separated via hyphen, not underscore, so you need "fr-CA", not "fr_CA" for example.
Please let me know if you want to use that method and need more concrete example.
与 Java 不同,Globalize 只有短(“f”)和长(“F”)日期和时间格式。所以我决定使用短的。
还请记住,全球化文化通过连字符而不是下划线分隔,因此您需要“fr-CA”,而不是“fr_CA”。
如果您想使用该方法并需要更具体的示例,请告诉我。
回答by Ben
Succeeded. Here is what I did:
成功了。这是我所做的:
Added to JSF a hidden input field so I can send JavaScript values to the server:
向 JSF 添加了一个隐藏的输入字段,以便我可以将 JavaScript 值发送到服务器:
<h:form prependId="false">
<h:inputText id="timezone_holder" value="#{bean.timezone}" styleClass="hide">
<f:ajax listener="#{bean.timezoneChangedListener}"></f:ajax>
</h:inputText>
</h:form>
Using the plugin above, I ran JavaScript
code that retrieved the offset of the browser.
使用上面的插件,我运行JavaScript
了检索浏览器偏移量的代码。
$(document).ready(function() {
var timezone = jstz.determine_timezone();
$("#timezone_holder").val(timezone.offset());
$("#timezone_holder").change();
});
When the timezone input is changed (initiated from the javascript code above) I run this code in the eventListener:
当时区输入更改时(从上面的 javascript 代码启动),我在 eventListener 中运行此代码:
String strFromJavaScript = getTimezone();
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
Locale browserLocale = request.getLocale();
TimeZone tz = TimeZone.getTimeZone("GMT" + strFromJavaScript);
// set time zone
SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy, HH:mm", browserLocale);
formatter.setTimeZone(tz);
Then, whenever I need to format a date I use the Date Formatter that was created above.
然后,每当我需要格式化日期时,我都会使用上面创建的日期格式化程序。
回答by Ghasfarost
Another option would be to create a cookie on a Javascript that executes when the home page is ready. After that, the cookie will exist on each subsequent request and would be available
另一种选择是在主页准备就绪时执行的 Javascript 上创建 cookie。之后,cookie 将存在于每个后续请求中并且可用
Your Javascript could use jQuery and jsTimezoneDetect
您的 Javascript 可以使用 jQuery 和jsTimezoneDetect
$(document).ready(function() {
setTimezoneCookie();
});
function setTimezoneCookie() {
var timezone = jstz.determine().name();
if (null == getCookie("timezoneCookie")) {
document.cookie = "timezoneCookie=" + timezone;
}
}
function getCookie(cookieName) {
var cookieValue = document.cookie;
var cookieStart = cookieValue.indexOf(" " + cookieName + "=");
if (cookieStart == -1) {
cookieStart = cookieValue.indexOf(cookieName + "=");
}
if (cookieStart == -1) {
cookieValue = null;
} else {
cookieStart = cookieValue.indexOf("=", cookieStart) + 1;
var cookieEnd = cookieValue.indexOf(";", cookieStart);
if (cookieEnd == -1) {
cookieEnd = cookieValue.length;
}
cookieValue = unescape(cookieValue.substring(cookieStart, cookieEnd));
}
return cookieValue;
}
Your Facelet would then use the cookie's value if it exists:
如果存在,您的 Facelet 将使用 cookie 的值:
<h:outputText value="#{bean.time}">
<f:convertDateTime
dateStyle="full"
timeStyle="full"
type="both"
timeZone="#{cookie.timezoneCookie.value}">
</f:convertDateTime>
</h:outputText>
回答by Mr.J4mes
You may want to try jsTimezoneDetectto detect timezone on the client side and send to the server.
您可能想尝试jsTimezoneDetect来检测客户端的时区并发送到服务器。
UPDATE:to get a user's Locale, you can try the following:
更新:要获取用户的语言环境,您可以尝试以下操作:
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Locale locale = request.getLocale();
Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration containing one Locale, the default locale for the server.
返回一个 Locale 对象的枚举,以从首选语言环境开始的降序表示,基于 Accept-Language 标头的客户端可接受的语言环境。如果客户端请求不提供 Accept-Language 标头,则此方法返回一个包含一个区域设置的枚举,即服务器的默认区域设置。
回答by Daniel
If all you need is to display time stamps with the users local time you dont need the Locale object (you need to add the users hours offset to GMT + 0 time), Y You need to send the value of timezone.offset() (from the example in the link) to the server (you can do it by using servlet post with parameter)
如果您只需要显示用户本地时间的时间戳,您不需要 Locale 对象(您需要将用户小时偏移量添加到 GMT + 0 时间),Y 您需要发送 timezone.offset() (从链接中的示例)到服务器(您可以通过使用带有参数的 servlet post 来完成)
and then add this offset to the date object created on your server (set your locale on the server to be GMT + 00)
然后将此偏移量添加到服务器上创建的日期对象(将服务器上的语言环境设置为 GMT + 00)
that way you will create time stamps with the correct time of the user that is logged into your web app
这样,您将使用登录到您的 Web 应用程序的用户的正确时间创建时间戳
(that's what I did myself...)
(这是我自己做的...)
回答by Adrian
You can also use it like this direct in JSF code:
您也可以直接在 JSF 代码中像这样使用它:
<script type="text/javascript">
$(document).ready(function () {
var timezone = jstz.determine_timezone();
$("#timezone_holder").val(timezone.name()); //use TimeZone name instead of offset
$("#timezone_holder").change();
});
</script>
Then you can reuse the timezonename in a JSF converter:
然后您可以在 JSF 转换器中重用时区名称:
<f:convertDateTime pattern="dd.MM.yyyy HH:mm" timeZone="#{bean.timezone}" />