Recipe 24.7 Formatting Dates in a Servlet


You want to format a date for display in a servlet based on the request's locale.


Use the java.text.DateFormat class.


Different countries have their own ways of displaying the date and time. The DateFormat class, like many of the classes in the java.text package, is "locale sensitive." Your code displays the date depending on the browser's language setting. All you have to do is pass the Locale object to the static DateFormat.getDateTimeInstance( ) method, as in the servlet of Example 24-8.

Example 24-8. Displaying a date String in a locale-sensitive manner
 package com.jspservletcookbook;  import java.text.DateFormat; import java.util.Date; import java.util.Locale; import java.util.ResourceBundle;  import javax.servlet.*; import javax.servlet.http.*;  public class DateLocaleServlet extends HttpServlet {  public void doGet(HttpServletRequest request,    HttpServletResponse response) throws ServletException, {            //Get the client's Locale       Locale locale = request.getLocale( );       ResourceBundle bundle = ResourceBundle.getBundle(         "i18n.WelcomeBundle",locale);       String welcome =  bundle.getString("Welcome");  String date = DateFormat.getDateTimeInstance(DateFormat.FULL,          DateFormat.SHORT, locale).format(new Date( ));  //Display the locale       response.setContentType("text/html"); out = response.getWriter( );       out.println("<html><head><title>"+welcome+"</title></head><body>");              out.println("<h2>"+bundle.getString("Hello") + " " +         bundle.getString("and") + " " +           welcome+"</h2>");  out.println(date+  "<br /><br />");  out.println("Locale: ");       out.println( locale.getLanguage( )+"_"+locale.getCountry( ) );              out.println("</body></html>");             } //doGet   //implement doPost and call doGet(request, response); } 

The DateFormat.getDateTimeInstance( ) method includes parameters in the form of constants (e.g., DateFormat.FULL ) that allow your code to customize the date format. Example 24-8 displays the date in a way that includes the name of the day of the week and a short form for the time. You can experiment with these constants in order to determine how browsers display the servlet's output. Figure 24-5 shows how the date is displayed in response to a German-language locale of "de_DE."

Figure 24-5. Displaying the date in a servlet according to the request's locale

See Also

The Javadoc for the DateFormat class:; Recipe 24.8 on formatting dates in a JSP.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: