Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 12 Localization

+" \n The currency symbol is " + currencyInstance.getSymbol()

+" \n The currency name is " + currencyInstance.getDisplayName());

}

}

It prints the following:

The currency code for locale en_US is: USD The currency symbol is $

The currency name is US Dollar

The output is self-explanatory. Note that for many locales where there is no symbol involved, getSymbol() will just return the currency code.

The DateFormat Class

The DateFormat class provides support for processing date and time in a locale-sensitive manner (the name simply says DateFormat, but it supports both date and time). Table 12-5 lists some of the important methods in the

DateFormat class.

Table 12-5.  Important Methods in the DateFormat Class

 

 

Method

Short Description

String format(Date date)

Formats the given date for the default locale and returns a textual

 

representation. Its overloaded version takes a StringBuffer and

 

position as arguments and returns a StringBuffer object; useful

 

if an existing StringBuffer needs to be formatted for date.

Date parse(String source)

Reads the given String according to the default locale conventions

 

to return a Date object; throws ParseException if it fails. It has an

 

overloaded version that takes ParsePosition (the position from

 

which to parse the String) as an additional argument.

String format(Date date)

Formats the given date for the default locale and returns a textual

 

representation.

static Locale[] getAvailableLocales()

Returns an array of Locales that are supported by the Java

 

runtime for date/time formatting.

static DateFormat getInstance()

Returns the default DateFormat instance that supports both date

 

and time; it uses DateFormat.SHORT style for both date and time.

static DateFormat getDateInstance()

Returns the DateFormat instance suitable for processing dates for

 

default locale; its two overloaded versions take style and Locale

 

as additional arguments.

static DateFormat getTimeInstance()

Returns the DateFormat instance suitable for processing time

 

for a default locale; its two overloaded versions take style and

 

Locale as additional arguments.

static DateFormat getDateTimeInstance()

Returns the DateFormat instance suitable for processing both

 

date and time for a default locale; its two overloaded versions take

 

style and Locale as additional arguments.

 

 

381

Chapter 12 Localization

Depending on the locale, the displayed date or time can be considerably different, as shown from the output of the program in Listing 12-12 for four locales.

Listing 12-12.  DatePrint.java

import java.util.*; import java.text.*;

// Class to demonstrate the use of DateFormat class to format the date and print it class DatePrint {

public static void main(String[] args) {

//the default constructor for the Date

//sets the date/time for current date/time Date today = new Date();

Locale [] locales = { Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.ITALY }; for(Locale locale : locales) {

// DateFormat.FULL refers to the full details of the date

DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale); System.out.println("Date in locale " + locale + " is: " + dateFormat. format(today));

}

}

}

When this program was run on Sept 4, 2012, it printed the following:

Date in locale en_CA is: Tuesday, September 4, 2012 Date in locale fr_FR is: mardi 4 septembre 2012

Date in locale de_DE is: Dienstag, 4. September 2012 Date in locale it_IT is: martedì 4 settembre 2012

This program gets an instance of the DateFormat class using one of the overloaded versions of the getDateInstance() method. This method takes the display format style as the first argument, and the locale to be used for formatting the date as the second argument. What are those display format styles? Listing 12-13 shows the four styles and how the dates look different for these styles.

Listing 12-13.  DateStyleFormats.java

import java.util.*; import java.text.*;

// Demonstrates the use of constants in DateFormat that determines the display style class DateStyleFormats {

public static void main(String []args) { Date now = new Date();

int [] dateStyleFormats = { DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL, DateFormat.DEFAULT};

System.out.println("Today's date in different styles are: ");

//print today's date in all four formats plus

//the default format in the default Locale for(int dateStyleFormat : dateStyleFormats) {

382

Chapter 12 Localization

DateFormat dateFormat = DateFormat.getDateInstance(dateStyleFormat); System.out.println(dateFormat.format(now));

}

}

} 

When run on Sept 5, 2012, it printed the following: 

Today's date in different styles are: 9/5/12

Sep 5, 2012 September 5, 2012

Wednesday, September 5, 2012 Sep 5, 2012 

As you can see, you can get an instance of DateFormat for a preferred style based on the need. The default style is

DateFormat.MEDIUM.

The DateFormat has three overloaded factory methods—getDateInstance(), getTimeInstance(), and getDateTimeInstance()—that return DateFormat instances for processing date, time, and both date and time, respectively. Listing 12-14 shows how to use them.

Listing 12-14.  DateTimePrint.java

import java.util.*; import java.text.*; 

// Class to demonstrate the use of DateFormat class to get date, time, or date with time class DateTimePrint {

public static void main(String []args) {

//the default constructor for the Date gets the current time and date Date today = new Date();

Locale [] locales =

{Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.ITALY };

//print the header first

System.out.printf("%5s \t %10s \t %10s \t %10s %n", "Locale", "Date", "Time", "Date with Time");

// print the date, time, and date & time for each locale for(Locale locale : locales) {

//DateFormat.SHORT is for giving the date or

//time details in compact format

DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

// now, for Date & Time, change the styles to MEDIUM and FULL DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat. MEDIUM, DateFormat.FULL, locale);

System.out.printf("%5s \t %10s \t %10s \t %20s %n", locale, dateFormat.format(today), timeFormat.format(today), dateTimeFormat.format(today));

}

}

} 

383

Chapter 12 Localization

When run on Sept 5, 2012 in the afternoon, it printed the following:

 

 

 

Locale

Date

Time

Date with Time

en_CA

05/09/12

2:32 PM

5-Sep-2012 2:32:56 o'clock PM GMT + 05:30

fr_FR

05/09/12

14:32

5 sept. 2012 14 h 32 GMT + 05:30

de_DE

05.09.12

14:32

05.09.2012 14:32 Uhr GMT + 05:30

it_IT

05/09/12

14.32

5-set-2012 14.32.56 GMT + 05:30

 

 

 

This program shows how to get instances of DateFormat for processing date, time, or both date and time. You can also see the effect of using different styles for different locales.

Until now you have only used DateFormat to process predefined date and time for different locales. If you want to create your own format or pattern for processing the date or time, can you do that? Yes, the SimpleDateFormat class provides this facility.

The SimpleDateFormat Class

SimpleDateFormat extends the DateFormat class. SimpleDateFormat uses the concept of a pattern string to format the date and time. Before you delve deeper into creating pattern strings, first look at a simple example to learn how to create a custom format for printing date and time (Listing 12-15).

Listing 12-15.  PatternStringExample.java

import java.util.*; import java.text.*;

// Use SimpleDateFormat for creating custom date and time formats as a pattern string class PatternStringExample {

public static void main(String []args) {

String pattern = "dd-MM-yy"; /* d for day, M for month, y for year */ SimpleDateFormat formatter = new SimpleDateFormat(pattern);

// the default Date constructor initializes to current date/time System.out.println(formatter.format(new Date()));

}

}

It prints the date in following format:

05-09-12

You encode the format of the date or time using letters to form a date or time pattern string. Usually these letters are repeated in the pattern. Note that the uppercase and lowercase letters can have similar or different meanings, so read the documentation carefully when trying to use these letters. For example, in dd-MM-yy, MM refers to month; however, in dd-mm-yy, mm refers to minutes!

In this program, you’ve given a simple example for creating a custom format for date. Similar letters are available for creating custom date and time pattern strings. Here is the list of important letters and their meanings for creating patterns for dates:

G

Era (BC/AD)

y

Year

Y

Week year

M

Month (in year)

w

Week (in year)

384

Chapter 12 Localization

W Week (in month) D Day (in year)

d Day (in month)

F Day of week in month E Day name in week

u Day number of week (value range 1-7)

Listing 12-16 is a program that uses simple to difficult pattern strings for creating custom date formats.

Listing 12-16.  CustomDatePatterns.java

import java.util.*; import java.text.*;

// Using an example, illustrates the use of "pattern strings" for printing dates class CustomDatePatterns {

public static void main(String []args) {

// patterns from simple to complex ones String [] dateFormats = {

"dd-MM-yyyy", /* d is day (in month), M is month, y is year */

"d '('E')' MMM, YYYY", /*E is name of the day (in week), Y is year*/ "w'th week of' YYYY", /* w is the week of the year */

"EEEE, dd'th' MMMM, YYYY" /*E is day name in the week */

};

Date today = new Date();

System.out.println("Default format for the date is " + DateFormat.getDateInstance().format(today)); for(String dateFormat : dateFormats) {

System.out.printf("Date in pattern \"%s\" is %s %n", dateFormat, new SimpleDateFormat(dateFormat).format(today));

}

}

}

In a sample run, it printed the following:

Default format for the date is Sep 5, 2012 Date in pattern "dd-MM-yyyy" is 05-09-2012

Date in pattern "d '('E')' MMM, YYYY" is 5 (Wed) Sep, 2012 Date in pattern "w'th week of' YYYY" is 36th week of 2012

Date in pattern "EEEE, dd'th' MMMM, YYYY" is Wednesday, 05th September, 2012

As you can see, repeating letters result in a longer form for an entry. For example, when you use E (which is the name of the day in the week), it prints Wed, whereas when you use EEEE, it prints the full form of the day name, which is Wednesday.

Another important thing to notice is how to print text within the given pattern string. For that you use text separated by single quotes, as in ‘within single quotes’ which will be printed as it is by the SimpleDateFormat. For example, ‘(‘E’)’ prints (Wed). If you give an incorrect pattern or forget to use single quotes for separating your text from pattern letters inside the pattern string, you’ll get an IllegalArgumentException exception for passing an “Illegal pattern.”

385

Chapter 12 Localization

Now, look at a similar example for creating custom time pattern strings. Here is the list of important letters useful for defining a custom time pattern:

a Marker for the text am/pm marker H Hour (value range 0-23)

k Hour (value range 1-24)

K Hour in am/pm (value range 0-11) h Hour in am/pm (value range 1-12)

m

Minute

s

Second

S

Millisecond

z

Time zone (general time zone format)

For more letters and their descriptions, see the JavaDoc for the SimpleDateFormat class. Listing 12-17 is a program that uses simple to difficult pattern strings for creating custom time formats.

Listing 12-17.  CustomTimePatterns.java

import java.util.*; import java.text.*;

// Using an example, illustrates the use of "pattern strings" for constructing custom time formats class TimePattern {

public static void main(String []args) {

// patterns from simple to complex ones String [] timeFormats = {

"h:mm", /* h is hour in am/pm (1-12), m is minute */

"hh 'o''clock'", /* '' is the escape sequence to print a single quote */ "H:mm a", /* H is hour in day (0-23), a is am/pm*/

"hh:mm:ss:SS", /* s is seconds, S is milliseconds */

"K:mm:ss a, zzzz" /*K is hour in am/pm(0-11), z is time zone */

};

Date today = new Date();

System.out.println("Default format for the time is " + DateFormat.getTimeInstance().format(today)); for(String timeFormat : timeFormats) {

System.out.printf("Time in pattern \"%s\" is %s %n", timeFormat, new SimpleDateFormat(timeFormat).format(today));

}

}

}

It printed the following:

Default format for the time is 3:10:05 PM Time in pattern "hh 'o''clock'" is 03 o'clock Time in pattern "h:mm" is 3:10

Time in pattern "H:mm a" is 15:10 PM

Time in pattern "hh:mm:ss:SS" is 03:10:05:355

Time in pattern "K:mm:ss a, zzzz" is 3:10:05 PM, GMT + 05:30

Note that the output differs based on the pattern string you use in this program.

386

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]