2013-06-26 46 views
3

我需要在jsp页面的标签中打印当前区域设置的日期格式。
例如,如果用户的浏览器具有语言环境en_US,我想打印'mm/dd/yyyy';而如果它是en_GB'dd/mm/yy'。
有人可以建议获取该信息的jsp或jstl代码?在JSP页面中获取当前区域日期格式

EDIT 我不需要打印日期,我需要与当前区域根据准确打印字符串“日/月/年”或“毫米/日/年”。

回答

2

您需要使用I18N和L18N在你的JSP代码:

<%@ page import="java.io.*,java.util.Locale" %> 

request获取Locale

Locale locale = request.getLocale(); 

并应用DateFormat根据Locale

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); 
String formattedDate = df.format(yourDate); 

获得实际的格式为Locale,你可以尝试这样的事:

SimpleDateFormat sf = (SimpleDateFormat) df; 
String pattern = sf.toLocalizedPattern(); 

使用JSTL的formatDate

当您使用JSTL格式标记<fmt:formatDate>和,JSTL自动处理区域设置分辨率。根据浏览器的区域设置,JSTL将显示日期和数字。

<fmt:formatDate value="${date}" type="both" dateStyle="full" timeStyle="short" /> 
+0

不错,但我想知道的格式是什么,因为要在标签打印根据当前区域设置'dd/mm/yyyy'或'mm/dd/yyyy' – daniele

+0

如何获得该结果? – daniele

0
<fmt:setLocale value="en_US" scope="session"/> 

或指this

1

试试这个

<%@ page import="java.io.*,java.util.Locale" %> 
<%@ page import="javax.servlet.*,javax.servlet.http.* "%> 
<%@ page import="java.text.DateFormat,java.util.Date" %> 

<% 
String title = "Locale Specific Dates"; 
//Get the client's Locale 
Locale locale = request.getLocale(); 
String date = DateFormat.getDateTimeInstance(
           DateFormat.FULL, 
           DateFormat.SHORT, 
           locale).format(new Date()); 
%> 
<html> 
<head> 
<title><% out.print(title); %></title> 
</head> 
<body> 
<center> 
<h1><% out.print(title); %></h1> 
</center> 
<div align="center"> 
<p>Local Date: <% out.print(date); %></p> 
</div> 
</body> 
</html> 
-1

看那java.util.ResourceBundle类,主要是getBundle()方法。 (您可以使用此,或实现类似的机制。为了让你可以使用下面的代码区域设置信息...

Locale rLocale = request.getLocale(); 
ResourceBundle bundle = ResourceBundle.getBundle("MyLocale", rLocale); 
Locale selectedLocale = bundle.getLocale(); 
相关问题