The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Dates and Times › Formating dates and times

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
      • Calendars
      • Formating dates and times
        • Format a time amount
        • Format a time interval
        • Format and cast a date to a timezone
        • Get all time zone ids
        • Get an array of day names
        • Get an array of timezone ids for offset
        • Get the best date format pattern
        • Get the display name for a Timezone
        • Parse a formatted date string
    • Numerical Systems
    • Misc
    • Resource Bundles
    • Unicode, Transliteration, and Charactersets

Parse a formatted date string

Problem:

You want to parse a localized date string to a Java Date.

Solution:

As important as date formatting is, you have to be able to parse the formatted dates.  Parsing a date is very similar to formatting the date.  You just call the parse method on a DateFormat instance.

 

One important point is you need to specify the length of the DateFormat.  This can be difficult to know in advance sometimes.  You can wrap the parse attempt in a try catch to trap the ParseException and change the length of the DateFormat until you return a success.

 

To parse a date:

//Get a Locale
Locale chinese = new Locale("zh","CN");
//Get an instance of DateFormat.
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, chinese);
System.out.println(df.format(new Date()));
//Parse the date
//We need to handle the ParseException the parse method can throw
//The length specified in the DateFormat.getDateInstance method has to be the
//same as the string you are trying to parse, or you will get a ParseException in many cases.
try {
    //parse(String str) returns a Date
    Date date = df.parse("2008年11月30日 星期日");
    System.out.println(date.toString());
} catch (ParseException e) {
    e.printStackTrace();
}


 

The output:

2008年11月30日 星期日 Sun Nov 30 00:00:00 EST 2008

‹ Get the display name for a Timezone up Numerical Systems ›
  • date
  • Java
  • parse
  • Printer-friendly version
  • Add new comment

If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.

This site is ad supported.  I hope you find something among our sponsors worth clicking. ;)

i18n search

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author