Tuesday, September 22, 2009

Formatting dates in Java

In this post I will write about formatting dates in Java in different formats (patterns).

The Java classes that I will be using in the examples are:

The class Date represents a specific instant in time, with millisecond precision.

Format is an abstract base class for formatting locale-sensitive information such as dates, messages, and numbers.

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

A pattern of special characters is used to specify the format of the date. This example demonstrates some of the characters. For a complete listing, see the javadoc documentation for the SimpleDateFormat class.

Note: default locale (which, in the author's case) is Locale.ENGLISH. If the example is run in a different locale, the text (e.g., month names) will not be there: This example formats dates using the  same.

   

    Format formatter; 
   
    // The year
    formatter = new SimpleDateFormat("yy");    // 02
    formatter = new SimpleDateFormat("yyyy");  // 2002
   
    // The month
    formatter = new SimpleDateFormat("M");     // 1
    formatter = new SimpleDateFormat("MM");    // 01
    formatter = new SimpleDateFormat("MMM");   // Jan
    formatter = new SimpleDateFormat("MMMM");  // January
   
    // The day
    formatter = new SimpleDateFormat("d");     // 9
    formatter = new SimpleDateFormat("dd");    // 09
   
    // The day in week
    formatter = new SimpleDateFormat("E");     // Wed
    formatter = new SimpleDateFormat("EEEE");  // Wednesday
   
    // Get today's date
    Date date = new Date();
   
    // Some examples
    formatter = new SimpleDateFormat("MM/dd/yy");
    String s = formatter.format(date);
    // 01/09/02
   
    formatter = new SimpleDateFormat("dd-MMM-yy");
    s = formatter.format(date);
    // 29-Jan-02

1 comments:

Varun Mehta said...

nice formatting

Post a Comment