Get current locale date format in a JSP page

13,677

Solution 1

You need to use I18N and L18N in your JSP code :

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

Get the Locale from the request:

 Locale locale = request.getLocale();

And apply the DateFormat based on Locale.

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

To get the actual format for a Locale , you can try something like this :

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

Using JSTL's formatDate :

When you use JSTL format tag <fmt:formatDate> and <fmt:formatNumber>, JSTL automatically takes care of locale resolution. Depending on the browser’s locale setting JSTL will display the date and numbers.

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

Solution 2

Try this

<%@ 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>
Share:
13,677

Related videos on Youtube

cloudy_weather
Author by

cloudy_weather

Updated on September 14, 2022

Comments

  • cloudy_weather
    cloudy_weather about 1 year

    I need to print in a label in a jsp page the date format in the current locale.
    For example, if the browser of the user has the locale en_US, I would like to print 'mm/dd/yyyy'; while if it is en_GB 'dd/mm/yy'.
    Can someone suggest the jsp or jstl code for getting that info?

    EDIT I dont need to print the date, I need to print exactly the string 'dd/mm/yyyy' or 'mm/dd/yyyy' according with the current locale.

  • cloudy_weather
    cloudy_weather over 10 years
    okay, but I want to know what the format is, because want to print in a label 'dd/mm/yyyy' or 'mm/dd/yyyy' according to the current locale
  • cloudy_weather
    cloudy_weather over 10 years
    how can I achieve that result?