The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples] > Dates  [4 examples]

e322. Formatting and Parsing a Date Using Default Formats

Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG, and FULL. The SHORT format consists entirely of numbers while the FULL format contains most of the date components. There is also a default format called DEFAULT and is the same as MEDIUM.

Note: This example formats dates using the 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 the same.

    // Format
    Date date = new Date();
    
    String s = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
    // 2/16/02
    
    s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    // Feb 16, 2002
    
    s = DateFormat.getDateInstance(DateFormat.LONG).format(date);
    // February 16, 2002
    
    s = DateFormat.getDateInstance(DateFormat.FULL).format(date);
    // Saturday, February 16, 2002
    
    // This is same as MEDIUM
    s = DateFormat.getDateInstance().format(date);
    // Feb 16, 2002
    
    // This is same as MEDIUM
    s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
    // Feb 16, 2002
    
    // Parse
    try {
        date = DateFormat.getDateInstance(DateFormat.DEFAULT).parse("Feb 16, 2002");
    } catch (ParseException e) {
    }

 Related Examples
e320. Formatting a Date Using a Custom Format
e321. Parsing a Date Using a Custom Format
e323. Formatting and Parsing a Date for a Locale

See also: Messsages    Numbers    Times    Words and Sentences   


© 2002 Addison-Wesley.