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

Get the best date format pattern

 Problem:

You know what parts of a date you want to display but you don't know the exact pattern to use.

Solution:

Often a Java programmer will know what type of pattern he wants, but not exactly what the pattern would be.  With icu4j's DateTimePatternGenerator you can specify a pattern skeleton, and it will return the most appropriate localized match.

 

To get the best pattern for the skeleton, "MMMddYYYYH" in Japanese:

//Get a Locale object

ULocale locale = new ULocale("ja_JP");

//Get an instance of the DatePatternGenerator for the locale

DateTimePatternGenerator dp = DateTimePatternGenerator.getInstance(locale);

//Get the best pattern match

String best = dp.getBestPattern("MMMddYYYYHH");

//output the best pattern match

System.out.println(best);

//Get a DateFormat for the pattern

DateFormat df = new SimpleDateFormat(best);

//output a formatted date

System.out.println(df.format(new Date()));

 


The output:

 

YYYY年MM月dd日 HH

2008年12月06日 15

 

As you can see the closest match uses a 4 digit year followed by a year symbol, a 2 digit month followed by a month symbol, a 2 digit day followed by a day symbol, and a 0~24 hour.

 

 

‹ Get an array of timezone ids for offset up Get the display name for a Timezone ›
  • date pattern
  • DateTimePatternGenerator
  • 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