Source Code Cross Referenced for DateFormat.java in  » 6.0-JDK-Core » text » java » text » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » text » java.text 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001        /*
002         * Copyright 1996-2005 Sun Microsystems, Inc.  All Rights Reserved.
003         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004         *
005         * This code is free software; you can redistribute it and/or modify it
006         * under the terms of the GNU General Public License version 2 only, as
007         * published by the Free Software Foundation.  Sun designates this
008         * particular file as subject to the "Classpath" exception as provided
009         * by Sun in the LICENSE file that accompanied this code.
010         *
011         * This code is distributed in the hope that it will be useful, but WITHOUT
012         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014         * version 2 for more details (a copy is included in the LICENSE file that
015         * accompanied this code).
016         *
017         * You should have received a copy of the GNU General Public License version
018         * 2 along with this work; if not, write to the Free Software Foundation,
019         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020         *
021         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022         * CA 95054 USA or visit www.sun.com if you need additional information or
023         * have any questions.
024         */
025
026        /*
027         * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
028         * (C) Copyright IBM Corp. 1996 - All Rights Reserved
029         *
030         *   The original version of this source code and documentation is copyrighted
031         * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
032         * materials are provided under terms of a License Agreement between Taligent
033         * and Sun. This technology is protected by multiple US and International
034         * patents. This notice and attribution to Taligent may not be removed.
035         *   Taligent is a registered trademark of Taligent, Inc.
036         *
037         */
038
039        package java.text;
040
041        import java.io.InvalidObjectException;
042        import java.text.spi.DateFormatProvider;
043        import java.util.Calendar;
044        import java.util.Date;
045        import java.util.GregorianCalendar;
046        import java.util.HashMap;
047        import java.util.Locale;
048        import java.util.Map;
049        import java.util.MissingResourceException;
050        import java.util.ResourceBundle;
051        import java.util.TimeZone;
052        import java.util.spi.LocaleServiceProvider;
053        import sun.util.LocaleServiceProviderPool;
054
055        /**
056         * DateFormat is an abstract class for date/time formatting subclasses which
057         * formats and parses dates or time in a language-independent manner.
058         * The date/time formatting subclass, such as SimpleDateFormat, allows for
059         * formatting (i.e., date -> text), parsing (text -> date), and
060         * normalization.  The date is represented as a <code>Date</code> object or
061         * as the milliseconds since January 1, 1970, 00:00:00 GMT.
062         *
063         * <p>DateFormat provides many class methods for obtaining default date/time
064         * formatters based on the default or a given locale and a number of formatting
065         * styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More
066         * detail and examples of using these styles are provided in the method
067         * descriptions.
068         *
069         * <p>DateFormat helps you to format and parse dates for any locale.
070         * Your code can be completely independent of the locale conventions for
071         * months, days of the week, or even the calendar format: lunar vs. solar.
072         *
073         * <p>To format a date for the current Locale, use one of the
074         * static factory methods:
075         * <pre>
076         *  myString = DateFormat.getDateInstance().format(myDate);
077         * </pre>
078         * <p>If you are formatting multiple dates, it is
079         * more efficient to get the format and use it multiple times so that
080         * the system doesn't have to fetch the information about the local
081         * language and country conventions multiple times.
082         * <pre>
083         *  DateFormat df = DateFormat.getDateInstance();
084         *  for (int i = 0; i < myDate.length; ++i) {
085         *    output.println(df.format(myDate[i]) + "; ");
086         *  }
087         * </pre>
088         * <p>To format a date for a different Locale, specify it in the
089         * call to getDateInstance().
090         * <pre>
091         *  DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
092         * </pre>
093         * <p>You can use a DateFormat to parse also.
094         * <pre>
095         *  myDate = df.parse(myString);
096         * </pre>
097         * <p>Use getDateInstance to get the normal date format for that country.
098         * There are other static factory methods available.
099         * Use getTimeInstance to get the time format for that country.
100         * Use getDateTimeInstance to get a date and time format. You can pass in 
101         * different options to these factory methods to control the length of the
102         * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends
103         * on the locale, but generally:
104         * <ul><li>SHORT is completely numeric, such as 12.13.52 or 3:30pm
105         * <li>MEDIUM is longer, such as Jan 12, 1952
106         * <li>LONG is longer, such as January 12, 1952 or 3:30:32pm
107         * <li>FULL is pretty completely specified, such as
108         * Tuesday, April 12, 1952 AD or 3:30:42pm PST.
109         * </ul>
110         *
111         * <p>You can also set the time zone on the format if you wish.
112         * If you want even more control over the format or parsing,
113         * (or want to give your users more control),
114         * you can try casting the DateFormat you get from the factory methods
115         * to a SimpleDateFormat. This will work for the majority
116         * of countries; just remember to put it in a try block in case you
117         * encounter an unusual one.
118         *
119         * <p>You can also use forms of the parse and format methods with
120         * ParsePosition and FieldPosition to
121         * allow you to
122         * <ul><li>progressively parse through pieces of a string.
123         * <li>align any particular field, or find out where it is for selection
124         * on the screen.
125         * </ul>
126         *
127         * <h4><a name="synchronization">Synchronization</a></h4>
128         *
129         * <p>
130         * Date formats are not synchronized.
131         * It is recommended to create separate format instances for each thread.
132         * If multiple threads access a format concurrently, it must be synchronized
133         * externally.
134         *
135         * @see          Format
136         * @see          NumberFormat
137         * @see          SimpleDateFormat
138         * @see          java.util.Calendar
139         * @see          java.util.GregorianCalendar
140         * @see          java.util.TimeZone
141         * @version      1.63 05/05/07
142         * @author       Mark Davis, Chen-Lieh Huang, Alan Liu
143         */
144        public abstract class DateFormat extends Format {
145
146            /**
147             * The calendar that <code>DateFormat</code> uses to produce the time field
148             * values needed to implement date and time formatting.  Subclasses should
149             * initialize this to a calendar appropriate for the locale associated with
150             * this <code>DateFormat</code>.
151             * @serial
152             */
153            protected Calendar calendar;
154
155            /**
156             * The number formatter that <code>DateFormat</code> uses to format numbers
157             * in dates and times.  Subclasses should initialize this to a number format
158             * appropriate for the locale associated with this <code>DateFormat</code>.
159             * @serial
160             */
161            protected NumberFormat numberFormat;
162
163            /**
164             * Useful constant for ERA field alignment.
165             * Used in FieldPosition of date/time formatting.
166             */
167            public final static int ERA_FIELD = 0;
168            /**
169             * Useful constant for YEAR field alignment.
170             * Used in FieldPosition of date/time formatting.
171             */
172            public final static int YEAR_FIELD = 1;
173            /**
174             * Useful constant for MONTH field alignment.
175             * Used in FieldPosition of date/time formatting.
176             */
177            public final static int MONTH_FIELD = 2;
178            /**
179             * Useful constant for DATE field alignment.
180             * Used in FieldPosition of date/time formatting.
181             */
182            public final static int DATE_FIELD = 3;
183            /**
184             * Useful constant for one-based HOUR_OF_DAY field alignment.
185             * Used in FieldPosition of date/time formatting.
186             * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
187             * For example, 23:59 + 01:00 results in 24:59.
188             */
189            public final static int HOUR_OF_DAY1_FIELD = 4;
190            /**
191             * Useful constant for zero-based HOUR_OF_DAY field alignment.
192             * Used in FieldPosition of date/time formatting.
193             * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
194             * For example, 23:59 + 01:00 results in 00:59.
195             */
196            public final static int HOUR_OF_DAY0_FIELD = 5;
197            /**
198             * Useful constant for MINUTE field alignment.
199             * Used in FieldPosition of date/time formatting.
200             */
201            public final static int MINUTE_FIELD = 6;
202            /**
203             * Useful constant for SECOND field alignment.
204             * Used in FieldPosition of date/time formatting.
205             */
206            public final static int SECOND_FIELD = 7;
207            /**
208             * Useful constant for MILLISECOND field alignment.
209             * Used in FieldPosition of date/time formatting.
210             */
211            public final static int MILLISECOND_FIELD = 8;
212            /**
213             * Useful constant for DAY_OF_WEEK field alignment.
214             * Used in FieldPosition of date/time formatting.
215             */
216            public final static int DAY_OF_WEEK_FIELD = 9;
217            /**
218             * Useful constant for DAY_OF_YEAR field alignment.
219             * Used in FieldPosition of date/time formatting.
220             */
221            public final static int DAY_OF_YEAR_FIELD = 10;
222            /**
223             * Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.
224             * Used in FieldPosition of date/time formatting.
225             */
226            public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
227            /**
228             * Useful constant for WEEK_OF_YEAR field alignment.
229             * Used in FieldPosition of date/time formatting.
230             */
231            public final static int WEEK_OF_YEAR_FIELD = 12;
232            /**
233             * Useful constant for WEEK_OF_MONTH field alignment.
234             * Used in FieldPosition of date/time formatting.
235             */
236            public final static int WEEK_OF_MONTH_FIELD = 13;
237            /**
238             * Useful constant for AM_PM field alignment.
239             * Used in FieldPosition of date/time formatting.
240             */
241            public final static int AM_PM_FIELD = 14;
242            /**
243             * Useful constant for one-based HOUR field alignment.
244             * Used in FieldPosition of date/time formatting.
245             * HOUR1_FIELD is used for the one-based 12-hour clock.
246             * For example, 11:30 PM + 1 hour results in 12:30 AM.
247             */
248            public final static int HOUR1_FIELD = 15;
249            /**
250             * Useful constant for zero-based HOUR field alignment.
251             * Used in FieldPosition of date/time formatting.
252             * HOUR0_FIELD is used for the zero-based 12-hour clock.
253             * For example, 11:30 PM + 1 hour results in 00:30 AM.
254             */
255            public final static int HOUR0_FIELD = 16;
256            /**
257             * Useful constant for TIMEZONE field alignment.
258             * Used in FieldPosition of date/time formatting.
259             */
260            public final static int TIMEZONE_FIELD = 17;
261
262            // Proclaim serial compatibility with 1.1 FCS
263            private static final long serialVersionUID = 7218322306649953788L;
264
265            /**
266             * Overrides Format.
267             * Formats a time object into a time string. Examples of time objects
268             * are a time value expressed in milliseconds and a Date object.
269             * @param obj must be a Number or a Date.
270             * @param toAppendTo the string buffer for the returning time string.
271             * @return the string buffer passed in as toAppendTo, with formatted text appended.
272             * @param fieldPosition keeps track of the position of the field
273             * within the returned string.
274             * On input: an alignment field,
275             * if desired. On output: the offsets of the alignment field. For
276             * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
277             * if the given fieldPosition is DateFormat.YEAR_FIELD, the
278             * begin index and end index of fieldPosition will be set to
279             * 0 and 4, respectively.
280             * Notice that if the same time field appears
281             * more than once in a pattern, the fieldPosition will be set for the first
282             * occurrence of that time field. For instance, formatting a Date to
283             * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
284             * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
285             * the begin index and end index of fieldPosition will be set to
286             * 5 and 8, respectively, for the first occurrence of the timezone
287             * pattern character 'z'.
288             * @see java.text.Format
289             */
290            public final StringBuffer format(Object obj,
291                    StringBuffer toAppendTo, FieldPosition fieldPosition) {
292                if (obj instanceof  Date)
293                    return format((Date) obj, toAppendTo, fieldPosition);
294                else if (obj instanceof  Number)
295                    return format(new Date(((Number) obj).longValue()),
296                            toAppendTo, fieldPosition);
297                else
298                    throw new IllegalArgumentException(
299                            "Cannot format given Object as a Date");
300            }
301
302            /**
303             * Formats a Date into a date/time string.
304             * @param date a Date to be formatted into a date/time string.
305             * @param toAppendTo the string buffer for the returning date/time string.
306             * @param fieldPosition keeps track of the position of the field
307             * within the returned string.
308             * On input: an alignment field,
309             * if desired. On output: the offsets of the alignment field. For
310             * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
311             * if the given fieldPosition is DateFormat.YEAR_FIELD, the
312             * begin index and end index of fieldPosition will be set to
313             * 0 and 4, respectively.
314             * Notice that if the same time field appears
315             * more than once in a pattern, the fieldPosition will be set for the first
316             * occurrence of that time field. For instance, formatting a Date to
317             * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
318             * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
319             * the begin index and end index of fieldPosition will be set to
320             * 5 and 8, respectively, for the first occurrence of the timezone
321             * pattern character 'z'.
322             * @return the string buffer passed in as toAppendTo, with formatted text appended.
323             */
324            public abstract StringBuffer format(Date date,
325                    StringBuffer toAppendTo, FieldPosition fieldPosition);
326
327            /**
328             * Formats a Date into a date/time string.
329             * @param date the time value to be formatted into a time string.
330             * @return the formatted time string.
331             */
332            public final String format(Date date) {
333                return format(date, new StringBuffer(),
334                        DontCareFieldPosition.INSTANCE).toString();
335            }
336
337            /**
338             * Parses text from the beginning of the given string to produce a date.
339             * The method may not use the entire text of the given string.
340             * <p>
341             * See the {@link #parse(String, ParsePosition)} method for more information
342             * on date parsing.
343             *
344             * @param source A <code>String</code> whose beginning should be parsed.
345             * @return A <code>Date</code> parsed from the string.
346             * @exception ParseException if the beginning of the specified string
347             *            cannot be parsed.
348             */
349            public Date parse(String source) throws ParseException {
350                ParsePosition pos = new ParsePosition(0);
351                Date result = parse(source, pos);
352                if (pos.index == 0)
353                    throw new ParseException("Unparseable date: \"" + source
354                            + "\"", pos.errorIndex);
355                return result;
356            }
357
358            /**
359             * Parse a date/time string according to the given parse position.  For
360             * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
361             * that is equivalent to Date(837039928046).
362             *
363             * <p> By default, parsing is lenient: If the input is not in the form used
364             * by this object's format method but can still be parsed as a date, then
365             * the parse succeeds.  Clients may insist on strict adherence to the
366             * format by calling setLenient(false).
367             *
368             * @see java.text.DateFormat#setLenient(boolean)
369             *
370             * @param source  The date/time string to be parsed
371             *
372             * @param pos   On input, the position at which to start parsing; on
373             *              output, the position at which parsing terminated, or the
374             *              start position if the parse failed.
375             *
376             * @return      A Date, or null if the input could not be parsed
377             */
378            public abstract Date parse(String source, ParsePosition pos);
379
380            /**
381             * Parses text from a string to produce a <code>Date</code>.
382             * <p>
383             * The method attempts to parse text starting at the index given by
384             * <code>pos</code>.
385             * If parsing succeeds, then the index of <code>pos</code> is updated
386             * to the index after the last character used (parsing does not necessarily
387             * use all characters up to the end of the string), and the parsed
388             * date is returned. The updated <code>pos</code> can be used to
389             * indicate the starting point for the next call to this method.
390             * If an error occurs, then the index of <code>pos</code> is not
391             * changed, the error index of <code>pos</code> is set to the index of
392             * the character where the error occurred, and null is returned.
393             * <p>
394             * See the {@link #parse(String, ParsePosition)} method for more information
395             * on date parsing.
396             *
397             * @param source A <code>String</code>, part of which should be parsed.
398             * @param pos A <code>ParsePosition</code> object with index and error
399             *            index information as described above.
400             * @return A <code>Date</code> parsed from the string. In case of
401             *         error, returns null.
402             * @exception NullPointerException if <code>pos</code> is null.
403             */
404            public Object parseObject(String source, ParsePosition pos) {
405                return parse(source, pos);
406            }
407
408            /**
409             * Constant for full style pattern.
410             */
411            public static final int FULL = 0;
412            /**
413             * Constant for long style pattern.
414             */
415            public static final int LONG = 1;
416            /**
417             * Constant for medium style pattern.
418             */
419            public static final int MEDIUM = 2;
420            /**
421             * Constant for short style pattern.
422             */
423            public static final int SHORT = 3;
424            /**
425             * Constant for default style pattern.  Its value is MEDIUM.
426             */
427            public static final int DEFAULT = MEDIUM;
428
429            /**
430             * Gets the time formatter with the default formatting style
431             * for the default locale.
432             * @return a time formatter.
433             */
434            public final static DateFormat getTimeInstance() {
435                return get(DEFAULT, 0, 1, Locale.getDefault());
436            }
437
438            /**
439             * Gets the time formatter with the given formatting style
440             * for the default locale.
441             * @param style the given formatting style. For example,
442             * SHORT for "h:mm a" in the US locale.
443             * @return a time formatter.
444             */
445            public final static DateFormat getTimeInstance(int style) {
446                return get(style, 0, 1, Locale.getDefault());
447            }
448
449            /**
450             * Gets the time formatter with the given formatting style
451             * for the given locale.
452             * @param style the given formatting style. For example,
453             * SHORT for "h:mm a" in the US locale.
454             * @param aLocale the given locale.
455             * @return a time formatter.
456             */
457            public final static DateFormat getTimeInstance(int style,
458                    Locale aLocale) {
459                return get(style, 0, 1, aLocale);
460            }
461
462            /**
463             * Gets the date formatter with the default formatting style
464             * for the default locale.
465             * @return a date formatter.
466             */
467            public final static DateFormat getDateInstance() {
468                return get(0, DEFAULT, 2, Locale.getDefault());
469            }
470
471            /**
472             * Gets the date formatter with the given formatting style
473             * for the default locale.
474             * @param style the given formatting style. For example,
475             * SHORT for "M/d/yy" in the US locale.
476             * @return a date formatter.
477             */
478            public final static DateFormat getDateInstance(int style) {
479                return get(0, style, 2, Locale.getDefault());
480            }
481
482            /**
483             * Gets the date formatter with the given formatting style
484             * for the given locale.
485             * @param style the given formatting style. For example,
486             * SHORT for "M/d/yy" in the US locale.
487             * @param aLocale the given locale.
488             * @return a date formatter.
489             */
490            public final static DateFormat getDateInstance(int style,
491                    Locale aLocale) {
492                return get(0, style, 2, aLocale);
493            }
494
495            /**
496             * Gets the date/time formatter with the default formatting style
497             * for the default locale.
498             * @return a date/time formatter.
499             */
500            public final static DateFormat getDateTimeInstance() {
501                return get(DEFAULT, DEFAULT, 3, Locale.getDefault());
502            }
503
504            /**
505             * Gets the date/time formatter with the given date and time
506             * formatting styles for the default locale.
507             * @param dateStyle the given date formatting style. For example,
508             * SHORT for "M/d/yy" in the US locale.
509             * @param timeStyle the given time formatting style. For example,
510             * SHORT for "h:mm a" in the US locale.
511             * @return a date/time formatter.
512             */
513            public final static DateFormat getDateTimeInstance(int dateStyle,
514                    int timeStyle) {
515                return get(timeStyle, dateStyle, 3, Locale.getDefault());
516            }
517
518            /**
519             * Gets the date/time formatter with the given formatting styles
520             * for the given locale.
521             * @param dateStyle the given date formatting style.
522             * @param timeStyle the given time formatting style.
523             * @param aLocale the given locale.
524             * @return a date/time formatter.
525             */
526            public final static DateFormat getDateTimeInstance(int dateStyle,
527                    int timeStyle, Locale aLocale) {
528                return get(timeStyle, dateStyle, 3, aLocale);
529            }
530
531            /**
532             * Get a default date/time formatter that uses the SHORT style for both the
533             * date and the time.
534             */
535            public final static DateFormat getInstance() {
536                return getDateTimeInstance(SHORT, SHORT);
537            }
538
539            /**
540             * Returns an array of all locales for which the
541             * <code>get*Instance</code> methods of this class can return
542             * localized instances.
543             * The returned array represents the union of locales supported by the Java 
544             * runtime and by installed 
545             * {@link java.text.spi.DateFormatProvider DateFormatProvider} implementations.  
546             * It must contain at least a <code>Locale</code> instance equal to 
547             * {@link java.util.Locale#US Locale.US}.
548             *
549             * @return An array of locales for which localized
550             *         <code>DateFormat</code> instances are available.
551             */
552            public static Locale[] getAvailableLocales() {
553                LocaleServiceProviderPool pool = LocaleServiceProviderPool
554                        .getPool(DateFormatProvider.class);
555                return pool.getAvailableLocales();
556            }
557
558            /**
559             * Set the calendar to be used by this date format.  Initially, the default
560             * calendar for the specified or default locale is used.
561             * @param newCalendar the new Calendar to be used by the date format
562             */
563            public void setCalendar(Calendar newCalendar) {
564                this .calendar = newCalendar;
565            }
566
567            /**
568             * Gets the calendar associated with this date/time formatter.
569             * @return the calendar associated with this date/time formatter.
570             */
571            public Calendar getCalendar() {
572                return calendar;
573            }
574
575            /**
576             * Allows you to set the number formatter.
577             * @param newNumberFormat the given new NumberFormat.
578             */
579            public void setNumberFormat(NumberFormat newNumberFormat) {
580                this .numberFormat = newNumberFormat;
581            }
582
583            /**
584             * Gets the number formatter which this date/time formatter uses to
585             * format and parse a time.
586             * @return the number formatter which this date/time formatter uses.
587             */
588            public NumberFormat getNumberFormat() {
589                return numberFormat;
590            }
591
592            /**
593             * Sets the time zone for the calendar of this DateFormat object.
594             * @param zone the given new time zone.
595             */
596            public void setTimeZone(TimeZone zone) {
597                calendar.setTimeZone(zone);
598            }
599
600            /**
601             * Gets the time zone.
602             * @return the time zone associated with the calendar of DateFormat.
603             */
604            public TimeZone getTimeZone() {
605                return calendar.getTimeZone();
606            }
607
608            /**
609             * Specify whether or not date/time parsing is to be lenient.  With
610             * lenient parsing, the parser may use heuristics to interpret inputs that
611             * do not precisely match this object's format.  With strict parsing,
612             * inputs must match this object's format.
613             * @param lenient when true, parsing is lenient
614             * @see java.util.Calendar#setLenient
615             */
616            public void setLenient(boolean lenient) {
617                calendar.setLenient(lenient);
618            }
619
620            /**
621             * Tell whether date/time parsing is to be lenient.
622             */
623            public boolean isLenient() {
624                return calendar.isLenient();
625            }
626
627            /**
628             * Overrides hashCode
629             */
630            public int hashCode() {
631                return numberFormat.hashCode();
632                // just enough fields for a reasonable distribution
633            }
634
635            /**
636             * Overrides equals
637             */
638            public boolean equals(Object obj) {
639                if (this  == obj)
640                    return true;
641                if (obj == null || getClass() != obj.getClass())
642                    return false;
643                DateFormat other = (DateFormat) obj;
644                return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!
645                calendar.getFirstDayOfWeek() == other.calendar
646                        .getFirstDayOfWeek()
647                        && calendar.getMinimalDaysInFirstWeek() == other.calendar
648                                .getMinimalDaysInFirstWeek()
649                        && calendar.isLenient() == other.calendar.isLenient()
650                        && calendar.getTimeZone().equals(
651                                other.calendar.getTimeZone()) && numberFormat
652                        .equals(other.numberFormat));
653            }
654
655            /**
656             * Overrides Cloneable
657             */
658            public Object clone() {
659                DateFormat other = (DateFormat) super .clone();
660                other.calendar = (Calendar) calendar.clone();
661                other.numberFormat = (NumberFormat) numberFormat.clone();
662                return other;
663            }
664
665            /**
666             * Creates a DateFormat with the given time and/or date style in the given
667             * locale.
668             * @param timeStyle a value from 0 to 3 indicating the time format,
669             * ignored if flags is 2
670             * @param dateStyle a value from 0 to 3 indicating the time format,
671             * ignored if flags is 1
672             * @param flags either 1 for a time format, 2 for a date format,
673             * or 3 for a date/time format
674             * @param loc the locale for the format
675             */
676            private static DateFormat get(int timeStyle, int dateStyle,
677                    int flags, Locale loc) {
678                if ((flags & 1) != 0) {
679                    if (timeStyle < 0 || timeStyle > 3) {
680                        throw new IllegalArgumentException(
681                                "Illegal time style " + timeStyle);
682                    }
683                } else {
684                    timeStyle = -1;
685                }
686                if ((flags & 2) != 0) {
687                    if (dateStyle < 0 || dateStyle > 3) {
688                        throw new IllegalArgumentException(
689                                "Illegal date style " + dateStyle);
690                    }
691                } else {
692                    dateStyle = -1;
693                }
694                try {
695                    // Check whether a provider can provide an implementation that's closer 
696                    // to the requested locale than what the Java runtime itself can provide.
697                    LocaleServiceProviderPool pool = LocaleServiceProviderPool
698                            .getPool(DateFormatProvider.class);
699                    if (pool.hasProviders()) {
700                        DateFormat providersInstance = pool.getLocalizedObject(
701                                DateFormatGetter.INSTANCE, loc, timeStyle,
702                                dateStyle, flags);
703                        if (providersInstance != null) {
704                            return providersInstance;
705                        }
706                    }
707
708                    return new SimpleDateFormat(timeStyle, dateStyle, loc);
709                } catch (MissingResourceException e) {
710                    return new SimpleDateFormat("M/d/yy h:mm a");
711                }
712            }
713
714            /**
715             * Create a new date format.
716             */
717            protected DateFormat() {
718            }
719
720            /**
721             * Defines constants that are used as attribute keys in the
722             * <code>AttributedCharacterIterator</code> returned
723             * from <code>DateFormat.formatToCharacterIterator</code> and as
724             * field identifiers in <code>FieldPosition</code>.
725             * <p>
726             * The class also provides two methods to map
727             * between its constants and the corresponding Calendar constants.
728             *
729             * @since 1.4
730             * @see java.util.Calendar
731             */
732            public static class Field extends Format.Field {
733
734                // Proclaim serial compatibility with 1.4 FCS
735                private static final long serialVersionUID = 7441350119349544720L;
736
737                // table of all instances in this class, used by readResolve
738                private static final Map instanceMap = new HashMap(18);
739                // Maps from Calendar constant (such as Calendar.ERA) to Field
740                // constant (such as Field.ERA).
741                private static final Field[] calendarToFieldMapping = new Field[Calendar.FIELD_COUNT];
742
743                /** Calendar field. */
744                private int calendarField;
745
746                /**
747                 * Returns the <code>Field</code> constant that corresponds to
748                 * the <code>Calendar</code> constant <code>calendarField</code>.
749                 * If there is no direct mapping between the <code>Calendar</code>
750                 * constant and a <code>Field</code>, null is returned.
751                 *
752                 * @throws IllegalArgumentException if <code>calendarField</code> is
753                 *         not the value of a <code>Calendar</code> field constant.
754                 * @param calendarField Calendar field constant
755                 * @return Field instance representing calendarField.
756                 * @see java.util.Calendar
757                 */
758                public static Field ofCalendarField(int calendarField) {
759                    if (calendarField < 0
760                            || calendarField >= calendarToFieldMapping.length) {
761                        throw new IllegalArgumentException(
762                                "Unknown Calendar constant " + calendarField);
763                    }
764                    return calendarToFieldMapping[calendarField];
765                }
766
767                /**
768                 * Creates a <code>Field</code>.
769                 *
770                 * @param name the name of the <code>Field</code>
771                 * @param calendarField the <code>Calendar</code> constant this
772                 *        <code>Field</code> corresponds to; any value, even one
773                 *        outside the range of legal <code>Calendar</code> values may
774                 *        be used, but <code>-1</code> should be used for values
775                 *        that don't correspond to legal <code>Calendar</code> values
776                 */
777                protected Field(String name, int calendarField) {
778                    super (name);
779                    this .calendarField = calendarField;
780                    if (this .getClass() == DateFormat.Field.class) {
781                        instanceMap.put(name, this );
782                        if (calendarField >= 0) {
783                            // assert(calendarField < Calendar.FIELD_COUNT);
784                            calendarToFieldMapping[calendarField] = this ;
785                        }
786                    }
787                }
788
789                /**
790                 * Returns the <code>Calendar</code> field associated with this
791                 * attribute. For example, if this represents the hours field of
792                 * a <code>Calendar</code>, this would return
793                 * <code>Calendar.HOUR</code>. If there is no corresponding
794                 * <code>Calendar</code> constant, this will return -1.
795                 *
796                 * @return Calendar constant for this field
797                 * @see java.util.Calendar
798                 */
799                public int getCalendarField() {
800                    return calendarField;
801                }
802
803                /**
804                 * Resolves instances being deserialized to the predefined constants.
805                 *
806                 * @throws InvalidObjectException if the constant could not be
807                 *         resolved.
808                 * @return resolved DateFormat.Field constant
809                 */
810                protected Object readResolve() throws InvalidObjectException {
811                    if (this .getClass() != DateFormat.Field.class) {
812                        throw new InvalidObjectException(
813                                "subclass didn't correctly implement readResolve");
814                    }
815
816                    Object instance = instanceMap.get(getName());
817                    if (instance != null) {
818                        return instance;
819                    } else {
820                        throw new InvalidObjectException(
821                                "unknown attribute name");
822                    }
823                }
824
825                //
826                // The constants
827                //
828
829                /**
830                 * Constant identifying the era field.
831                 */
832                public final static Field ERA = new Field("era", Calendar.ERA);
833
834                /**
835                 * Constant identifying the year field.
836                 */
837                public final static Field YEAR = new Field("year",
838                        Calendar.YEAR);
839
840                /**
841                 * Constant identifying the month field.
842                 */
843                public final static Field MONTH = new Field("month",
844                        Calendar.MONTH);
845
846                /**
847                 * Constant identifying the day of month field.
848                 */
849                public final static Field DAY_OF_MONTH = new Field(
850                        "day of month", Calendar.DAY_OF_MONTH);
851
852                /**
853                 * Constant identifying the hour of day field, where the legal values
854                 * are 1 to 24.
855                 */
856                public final static Field HOUR_OF_DAY1 = new Field(
857                        "hour of day 1", -1);
858
859                /**
860                 * Constant identifying the hour of day field, where the legal values
861                 * are 0 to 23.
862                 */
863                public final static Field HOUR_OF_DAY0 = new Field(
864                        "hour of day", Calendar.HOUR_OF_DAY);
865
866                /**
867                 * Constant identifying the minute field.
868                 */
869                public final static Field MINUTE = new Field("minute",
870                        Calendar.MINUTE);
871
872                /**
873                 * Constant identifying the second field.
874                 */
875                public final static Field SECOND = new Field("second",
876                        Calendar.SECOND);
877
878                /**
879                 * Constant identifying the millisecond field.
880                 */
881                public final static Field MILLISECOND = new Field(
882                        "millisecond", Calendar.MILLISECOND);
883
884                /**
885                 * Constant identifying the day of week field.
886                 */
887                public final static Field DAY_OF_WEEK = new Field(
888                        "day of week", Calendar.DAY_OF_WEEK);
889
890                /**
891                 * Constant identifying the day of year field.
892                 */
893                public final static Field DAY_OF_YEAR = new Field(
894                        "day of year", Calendar.DAY_OF_YEAR);
895
896                /**
897                 * Constant identifying the day of week field.
898                 */
899                public final static Field DAY_OF_WEEK_IN_MONTH = new Field(
900                        "day of week in month", Calendar.DAY_OF_WEEK_IN_MONTH);
901
902                /**
903                 * Constant identifying the week of year field.
904                 */
905                public final static Field WEEK_OF_YEAR = new Field(
906                        "week of year", Calendar.WEEK_OF_YEAR);
907
908                /**
909                 * Constant identifying the week of month field.
910                 */
911                public final static Field WEEK_OF_MONTH = new Field(
912                        "week of month", Calendar.WEEK_OF_MONTH);
913
914                /**
915                 * Constant identifying the time of day indicator
916                 * (e.g. "a.m." or "p.m.") field.
917                 */
918                public final static Field AM_PM = new Field("am pm",
919                        Calendar.AM_PM);
920
921                /**
922                 * Constant identifying the hour field, where the legal values are
923                 * 1 to 12.
924                 */
925                public final static Field HOUR1 = new Field("hour 1", -1);
926
927                /**
928                 * Constant identifying the hour field, where the legal values are
929                 * 0 to 11.
930                 */
931                public final static Field HOUR0 = new Field("hour",
932                        Calendar.HOUR);
933
934                /**
935                 * Constant identifying the time zone field.
936                 */
937                public final static Field TIME_ZONE = new Field("time zone", -1);
938            }
939
940            /**
941             * Obtains a DateFormat instance from a DateFormatProvider 
942             * implementation.
943             */
944            private static class DateFormatGetter
945                    implements 
946                    LocaleServiceProviderPool.LocalizedObjectGetter<DateFormatProvider, DateFormat> {
947                private static final DateFormatGetter INSTANCE = new DateFormatGetter();
948
949                public DateFormat getObject(
950                        DateFormatProvider dateFormatProvider, Locale locale,
951                        String key, Object... params) {
952                    assert params.length == 3;
953
954                    int timeStyle = (Integer) params[0];
955                    int dateStyle = (Integer) params[1];
956                    int flags = (Integer) params[2];
957
958                    switch (flags) {
959                    case 1:
960                        return dateFormatProvider.getTimeInstance(timeStyle,
961                                locale);
962                    case 2:
963                        return dateFormatProvider.getDateInstance(dateStyle,
964                                locale);
965                    case 3:
966                        return dateFormatProvider.getDateTimeInstance(
967                                dateStyle, timeStyle, locale);
968                    default:
969                        assert false : "should not happen";
970                    }
971
972                    return null;
973                }
974            }
975        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.