The Java Developers Almanac 1.4


Order this book from Amazon.

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

e321. Parsing a Date Using a Custom Format

A pattern of special characters is used to specify the format of the date to parse. The same set of pattern characters are used to format and to parse dates. See e320 Formatting a Date Using a Custom Format for a listing of some pattern characters.

Note: This example parses 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.

    try {
        // Some examples
        DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
        Date date = (Date)formatter.parse("01/29/02");
    
        formatter = new SimpleDateFormat("dd-MMM-yy");
        date = (Date)formatter.parse("29-Jan-02");
    
        // Parse a date and time; see also
        // e317 Parsing the Time Using a Custom Format
        formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
        date = (Date)formatter.parse("2002.01.29.08.36.33");
    
        formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
        date = (Date)formatter.parse("Tue, 29 Jan 2002 22:14:02 -0500");
    } catch (ParseException e) {
    }

 Related Examples
e320. Formatting a Date Using a Custom Format
e322. Formatting and Parsing a Date Using Default Formats
e323. Formatting and Parsing a Date for a Locale

See also: Messsages    Numbers    Times    Words and Sentences   


© 2002 Addison-Wesley.