[ Team LiB ] Previous Section Next Section

Recipe 24.7 Formatting Dates in a Servlet

Problem

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

Solution

Use the java.text.DateFormat class.

Discussion

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, 
  java.io.IOException {
    
      //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");
      java.io.PrintWriter 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
figs/jsjc_2405.gif

See Also

The Javadoc for the DateFormat class: http://java.sun.com/j2se/1.4.1/docs/api/java/text/DateFormat.html; Recipe 24.8 on formatting dates in a JSP.

    [ Team LiB ] Previous Section Next Section