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

Format and cast a date to a timezone

Problem:

You want to format a date and cast it to a timezone.

Solution:

The Java DateFormat class can cast a date to a new time zone at the same time as formatting it.  This can be accomplished simply by specifying a TimeZone on the DateFormat object.

 

To format and cast a date to PST:

//Get a Locale.  In this case we are going to use Afrikans in South Africa
Locale afrikans = new Locale("af","ZA");
//Get a DateFormat instance.
//We specify length for date and time and a locale to format for.
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, afrikans);
//Get a TimeZone instance for a specified id.
//The ids are Olsen TimeZone ids
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
//Specify the time zone
df.setTimeZone(tz);
//output the format
System.out.println(df.format(new Date()));

 

Output Example:

viernes 5 de diciembre de 2007 06:49:46 PM PST

‹ Format a time interval up Get all time zone ids ›
  • date formatting
  • timezone
  • 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