Date and time formatting utilities and constants.
* *Formatting is performed using the * {@link org.apache.commons.lang.time.FastDateFormat} class.
* * @author Apache Ant - DateUtils * @author Stephane Bailliez * @author Stefan Bodewig * @author Stephen Colebourne * @author Gary Gregory * @since 2.0 * @version $Id: DateFormatUtils.java 615243 2008-01-25 15:20:32Z niallp $ */ public class DateFormatUtils { /** * ISO8601 formatter for date-time without time zone. * The format used is yyyy-MM-dd'T'HH:mm:ss. */ public static final FastDateFormat ISO_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); /** * ISO8601 formatter for date-time with time zone. * The format used is yyyy-MM-dd'T'HH:mm:ssZZ. */ public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ"); /** * ISO8601 formatter for date without time zone. * The format used is yyyy-MM-dd. */ public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd"); /** * ISO8601-like formatter for date with time zone. * The format used is yyyy-MM-ddZZ. * This pattern does not comply with the formal ISO8601 specification * as the standard does not allow a time zone without a time. */ public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ"); /** * ISO8601 formatter for time without time zone. * The format used is 'T'HH:mm:ss. */ public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ss"); /** * ISO8601 formatter for time with time zone. * The format used is 'T'HH:mm:ssZZ. */ public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ssZZ"); /** * ISO8601-like formatter for time without time zone. * The format used is HH:mm:ss. * This pattern does not comply with the formal ISO8601 specification * as the standard requires the 'T' prefix for times. */ public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss"); /** * ISO8601-like formatter for time with time zone. * The format used is HH:mm:ssZZ. * This pattern does not comply with the formal ISO8601 specification * as the standard requires the 'T' prefix for times. */ public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ"); /** * SMTP (and probably other) date headers. * The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale. */ public static final FastDateFormat SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); //----------------------------------------------------------------------- /** *DateFormatUtils instances should NOT be constructed in standard programming.
* *This constructor is public to permit tools that require a JavaBean instance * to operate.
*/ public DateFormatUtils() { super(); } /** *Formats a date/time into a specific pattern using the UTC time zone.
* * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @return the formatted date */ public static String formatUTC(long millis, String pattern) { return format(new Date(millis), pattern, UTC_TIME_ZONE, null); } /** *Formats a date/time into a specific pattern using the UTC time zone.
* * @param date the date to format * @param pattern the pattern to use to format the date * @return the formatted date */ public static String formatUTC(Date date, String pattern) { return format(date, pattern, UTC_TIME_ZONE, null); } /** *Formats a date/time into a specific pattern using the UTC time zone.
* * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param locale the locale to use, may benull
* @return the formatted date
*/
public static String formatUTC(long millis, String pattern, Locale locale) {
return format(new Date(millis), pattern, UTC_TIME_ZONE, locale);
}
public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
/**
* Formats a date/time into a specific pattern using the UTC time zone.
* * @param date the date to format * @param pattern the pattern to use to format the date * @param locale the locale to use, may benull
* @return the formatted date
*/
public static String formatUTC(Date date, String pattern, Locale locale) {
return format(date, pattern, UTC_TIME_ZONE, locale);
}
/**
* Formats a date/time into a specific pattern.
* * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @return the formatted date */ public static String format(long millis, String pattern) { return format(new Date(millis), pattern, null, null); } /** *Formats a date/time into a specific pattern.
* * @param date the date to format * @param pattern the pattern to use to format the date * @return the formatted date */ public static String format(Date date, String pattern) { return format(date, pattern, null, null); } /** *Formats a calendar into a specific pattern.
* * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @return the formatted calendar * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(Calendar calendar, String pattern) { return format(calendar, pattern, null, null); } /** *Formats a date/time into a specific pattern in a time zone.
* * @param millis the time expressed in milliseconds * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may benull
* @return the formatted date
*/
public static String format(long millis, String pattern, TimeZone timeZone) {
return format(new Date(millis), pattern, timeZone, null);
}
/**
* Formats a date/time into a specific pattern in a time zone.
* * @param date the date to format * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may benull
* @return the formatted date
*/
public static String format(Date date, String pattern, TimeZone timeZone) {
return format(date, pattern, timeZone, null);
}
/**
* Formats a calendar into a specific pattern in a time zone.
* * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param timeZone the time zone to use, may benull
* @return the formatted calendar
* @see FastDateFormat#format(Calendar)
* @since 2.4
*/
public static String format(Calendar calendar, String pattern, TimeZone timeZone) {
return format(calendar, pattern, timeZone, null);
}
/**
* Formats a date/time into a specific pattern in a locale.
* * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param locale the locale to use, may benull
* @return the formatted date
*/
public static String format(long millis, String pattern, Locale locale) {
return format(new Date(millis), pattern, null, locale);
}
/**
* Formats a date/time into a specific pattern in a locale.
* * @param date the date to format * @param pattern the pattern to use to format the date * @param locale the locale to use, may benull
* @return the formatted date
*/
public static String format(Date date, String pattern, Locale locale) {
return format(date, pattern, null, locale);
}
/**
* Formats a calendar into a specific pattern in a locale.
* * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param locale the locale to use, may benull
* @return the formatted calendar
* @see FastDateFormat#format(Calendar)
* @since 2.4
*/
public static String format(Calendar calendar, String pattern, Locale locale) {
return format(calendar, pattern, null, locale);
}
/**
* Formats a date/time into a specific pattern in a time zone and locale.
* * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may benull
* @param locale the locale to use, may be null
* @return the formatted date
*/
public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {
return format(new Date(millis), pattern, timeZone, locale);
}
/**
* Formats a date/time into a specific pattern in a time zone and locale.
* * @param date the date to format * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may benull
* @param locale the locale to use, may be null
* @return the formatted date
*/
public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(date);
}
/**
* Formats a calendar into a specific pattern in a time zone and locale.
* * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param timeZone the time zone to use, may benull
* @param locale the locale to use, may be null
* @return the formatted calendar
* @see FastDateFormat#format(Calendar)
* @since 2.4
*/
public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(calendar);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* FastDateFormat is a fast and thread-safe version of * {@link java.text.SimpleDateFormat}.
* *This class can be used as a direct replacement to
* SimpleDateFormat
in most formatting situations.
* This class is especially useful in multi-threaded server environments.
* SimpleDateFormat
is not thread-safe in any JDK version,
* nor will it be as Sun have closed the bug/RFE.
*
Only formatting is supported, but all patterns are compatible with * SimpleDateFormat (except time zones - see below).
* *Java 1.4 introduced a new pattern letter, 'Z'
, to represent
* time zones in RFC822 format (eg. +0800
or -1100
).
* This pattern letter can be used here (on all JDK versions).
In addition, the pattern 'ZZ'
has been made to represent
* ISO8601 full format time zones (eg. +08:00
or -11:00
).
* This introduces a minor incompatibility with Java 1.4, but at a gain of
* useful functionality.
Gets a formatter instance using the default pattern in the * default locale.
* * @return a date/time formatter */ public static FastDateFormat getInstance() { return getInstance(getDefaultPattern(), null, null); } /** *Gets a formatter instance using the specified pattern in the * default locale.
* * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern) { return getInstance(pattern, null, null); } /** *Gets a formatter instance using the specified pattern and * time zone.
* * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern, TimeZone timeZone) { return getInstance(pattern, timeZone, null); } /** *Gets a formatter instance using the specified pattern and * locale.
* * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern, Locale locale) { return getInstance(pattern, null, locale); } /** *Gets a formatter instance using the specified pattern, time zone * and locale.
* * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid * ornull
*/
public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale);
FastDateFormat format = (FastDateFormat) cInstanceCache.get(emptyFormat);
if (format == null) {
format = emptyFormat;
format.init(); // convert shell format into usable one
cInstanceCache.put(format, format); // this is OK!
}
return format;
}
//-----------------------------------------------------------------------
/**
* Gets a date formatter instance using the specified style in the * default time zone and locale.
* * @param style date style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style) { return getDateInstance(style, null, null); } /** *Gets a date formatter instance using the specified style and * locale in the default time zone.
* * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style, Locale locale) { return getDateInstance(style, null, locale); } /** *Gets a date formatter instance using the specified style and * time zone in the default locale.
* * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style, TimeZone timeZone) { return getDateInstance(style, timeZone, null); } /** *Gets a date formatter instance using the specified style, time * zone and locale.
* * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined */ public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *Gets a time formatter instance using the specified style in the * default time zone and locale.
* * @param style time style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style) { return getTimeInstance(style, null, null); } /** *Gets a time formatter instance using the specified style and * locale in the default time zone.
* * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style, Locale locale) { return getTimeInstance(style, null, locale); } /** *Gets a time formatter instance using the specified style and * time zone in the default locale.
* * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted time * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) { return getTimeInstance(style, timeZone, null); } /** *Gets a time formatter instance using the specified style, time * zone and locale.
* * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted time * @param locale optional locale, overrides system locale * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined */ public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale != null) { key = new Pair(key, locale); } FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key); if (format == null) { if (locale == null) { locale = Locale.getDefault(); } try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cTimeInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *Gets a date/time formatter instance using the specified style * in the default time zone and locale.
* * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle) { return getDateTimeInstance(dateStyle, timeStyle, null, null); } /** *Gets a date/time formatter instance using the specified style and * locale in the default time zone.
* * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle, Locale locale) { return getDateTimeInstance(dateStyle, timeStyle, null, locale); } /** *Gets a date/time formatter instance using the specified style and * time zone in the default locale.
* * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle, TimeZone timeZone) { return getDateTimeInstance(dateStyle, timeStyle, timeZone, null); } /** *Gets a date/time formatter instance using the specified style, * time zone and locale.
* * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined */ public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone, Locale locale) { Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle)); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateTimeInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date time pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *Gets the time zone display name, using a cache for performance.
* * @param tz the zone to query * @param daylight true if daylight savings * @param style the style to useTimeZone.LONG
* or TimeZone.SHORT
* @param locale the locale to use
* @return the textual name of the time zone
*/
static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
String value = (String) cTimeZoneDisplayCache.get(key);
if (value == null) {
// This is a very slow call, so cache the results.
value = tz.getDisplayName(daylight, style, locale);
cTimeZoneDisplayCache.put(key, value);
}
return value;
}
/**
* Gets the default pattern.
* * @return the default pattern */ private static synchronized String getDefaultPattern() { if (cDefaultPattern == null) { cDefaultPattern = new SimpleDateFormat().toPattern(); } return cDefaultPattern; } // Constructor //----------------------------------------------------------------------- /** *Constructs a new FastDateFormat.
* * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone time zone to use,null
means use
* default for Date
and value within for
* Calendar
* @param locale locale, null
means use system
* default
* @throws IllegalArgumentException if pattern is invalid or
* null
*/
protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
super();
if (pattern == null) {
throw new IllegalArgumentException("The pattern must not be null");
}
mPattern = pattern;
mTimeZoneForced = (timeZone != null);
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
mTimeZone = timeZone;
mLocaleForced = (locale != null);
if (locale == null) {
locale = Locale.getDefault();
}
mLocale = locale;
}
/**
* Initializes the instance for first use.
*/ protected void init() { List rulesList = parsePattern(); mRules = (Rule[]) rulesList.toArray(new Rule[rulesList.size()]); int len = 0; for (int i=mRules.length; --i >= 0; ) { len += mRules[i].estimateLength(); } mMaxLengthEstimate = len; } // Parse the pattern //----------------------------------------------------------------------- /** *Returns a list of Rules given a pattern.
* * @return aList
of Rule objects
* @throws IllegalArgumentException if pattern is invalid
*/
protected List parsePattern() {
DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
List rules = new ArrayList();
String[] ERAs = symbols.getEras();
String[] months = symbols.getMonths();
String[] shortMonths = symbols.getShortMonths();
String[] weekdays = symbols.getWeekdays();
String[] shortWeekdays = symbols.getShortWeekdays();
String[] AmPmStrings = symbols.getAmPmStrings();
int length = mPattern.length();
int[] indexRef = new int[1];
for (int i = 0; i < length; i++) {
indexRef[0] = i;
String token = parseToken(mPattern, indexRef);
i = indexRef[0];
int tokenLen = token.length();
if (tokenLen == 0) {
break;
}
Rule rule;
char c = token.charAt(0);
switch (c) {
case 'G': // era designator (text)
rule = new TextField(Calendar.ERA, ERAs);
break;
case 'y': // year (number)
if (tokenLen >= 4) {
rule = selectNumberRule(Calendar.YEAR, tokenLen);
} else {
rule = TwoDigitYearField.INSTANCE;
}
break;
case 'M': // month in year (text and number)
if (tokenLen >= 4) {
rule = new TextField(Calendar.MONTH, months);
} else if (tokenLen == 3) {
rule = new TextField(Calendar.MONTH, shortMonths);
} else if (tokenLen == 2) {
rule = TwoDigitMonthField.INSTANCE;
} else {
rule = UnpaddedMonthField.INSTANCE;
}
break;
case 'd': // day in month (number)
rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
break;
case 'h': // hour in am/pm (number, 1..12)
rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
break;
case 'H': // hour in day (number, 0..23)
rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
break;
case 'm': // minute in hour (number)
rule = selectNumberRule(Calendar.MINUTE, tokenLen);
break;
case 's': // second in minute (number)
rule = selectNumberRule(Calendar.SECOND, tokenLen);
break;
case 'S': // millisecond (number)
rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
break;
case 'E': // day in week (text)
rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
break;
case 'D': // day in year (number)
rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
break;
case 'F': // day of week in month (number)
rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
break;
case 'w': // week in year (number)
rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
break;
case 'W': // week in month (number)
rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
break;
case 'a': // am/pm marker (text)
rule = new TextField(Calendar.AM_PM, AmPmStrings);
break;
case 'k': // hour in day (1..24)
rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
break;
case 'K': // hour in am/pm (0..11)
rule = selectNumberRule(Calendar.HOUR, tokenLen);
break;
case 'z': // time zone (text)
if (tokenLen >= 4) {
rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG);
} else {
rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT);
}
break;
case 'Z': // time zone (value)
if (tokenLen == 1) {
rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
} else {
rule = TimeZoneNumberRule.INSTANCE_COLON;
}
break;
case '\'': // literal text
String sub = token.substring(1);
if (sub.length() == 1) {
rule = new CharacterLiteral(sub.charAt(0));
} else {
rule = new StringLiteral(sub);
}
break;
default:
throw new IllegalArgumentException("Illegal pattern component: " + token);
}
rules.add(rule);
}
return rules;
}
/**
* Performs the parsing of tokens.
* * @param pattern the pattern * @param indexRef index references * @return parsed token */ protected String parseToken(String pattern, int[] indexRef) { StringBuffer buf = new StringBuffer(); int i = indexRef[0]; int length = pattern.length(); char c = pattern.charAt(i); if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { // Scan a run of the same character, which indicates a time // pattern. buf.append(c); while (i + 1 < length) { char peek = pattern.charAt(i + 1); if (peek == c) { buf.append(c); i++; } else { break; } } } else { // This will identify token as text. buf.append('\''); boolean inLiteral = false; for (; i < length; i++) { c = pattern.charAt(i); if (c == '\'') { if (i + 1 < length && pattern.charAt(i + 1) == '\'') { // '' is treated as escaped ' i++; buf.append(c); } else { inLiteral = !inLiteral; } } else if (!inLiteral && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { i--; break; } else { buf.append(c); } } } indexRef[0] = i; return buf.toString(); } /** *Gets an appropriate rule for the padding required.
* * @param field the field to get a rule for * @param padding the padding required * @return a new rule with the correct padding */ protected NumberRule selectNumberRule(int field, int padding) { switch (padding) { case 1: return new UnpaddedNumberField(field); case 2: return new TwoDigitNumberField(field); default: return new PaddedNumberField(field, padding); } } // Format methods //----------------------------------------------------------------------- /** *Formats a Date
, Calendar
or
* Long
(milliseconds) object.
Formats a millisecond long
value.
Formats a Date
object.
Formats a Calendar
object.
Formats a milliseond long
value into the
* supplied StringBuffer
.
Formats a Date
object into the
* supplied StringBuffer
.
Formats a Calendar
object into the
* supplied StringBuffer
.
Performs the formatting by applying the rules to the * specified calendar.
* * @param calendar the calendar to format * @param buf the buffer to format into * @return the specified string buffer */ protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) { Rule[] rules = mRules; int len = mRules.length; for (int i = 0; i < len; i++) { rules[i].appendTo(buf, calendar); } return buf; } // Parsing //----------------------------------------------------------------------- /** *Parsing is not supported.
* * @param source the string to parse * @param pos the parsing position * @returnnull
as not supported
*/
public Object parseObject(String source, ParsePosition pos) {
pos.setIndex(0);
pos.setErrorIndex(0);
return null;
}
// Accessors
//-----------------------------------------------------------------------
/**
* Gets the pattern used by this formatter.
* * @return the pattern, {@link java.text.SimpleDateFormat} compatible */ public String getPattern() { return mPattern; } /** *Gets the time zone used by this formatter.
* *This zone is always used for Date
formatting.
* If a Calendar
is passed in to be formatted, the
* time zone on that may be used depending on
* {@link #getTimeZoneOverridesCalendar()}.
Returns true
if the time zone of the
* calendar overrides the time zone of the formatter.
true
if time zone of formatter
* overridden for calendars
*/
public boolean getTimeZoneOverridesCalendar() {
return mTimeZoneForced;
}
/**
* Gets the locale used by this formatter.
* * @return the locale */ public Locale getLocale() { return mLocale; } /** *Gets an estimate for the maximum string length that the * formatter will produce.
* *The actual formatted length will almost always be less than or * equal to this amount.
* * @return the maximum formatted length */ public int getMaxLengthEstimate() { return mMaxLengthEstimate; } // Basics //----------------------------------------------------------------------- /** *Compares two objects for equality.
* * @param obj the object to compare to * @returntrue
if equal
*/
public boolean equals(Object obj) {
if (obj instanceof FastDateFormat == false) {
return false;
}
FastDateFormat other = (FastDateFormat) obj;
if (
(mPattern == other.mPattern || mPattern.equals(other.mPattern)) &&
(mTimeZone == other.mTimeZone || mTimeZone.equals(other.mTimeZone)) &&
(mLocale == other.mLocale || mLocale.equals(other.mLocale)) &&
(mTimeZoneForced == other.mTimeZoneForced) &&
(mLocaleForced == other.mLocaleForced)
) {
return true;
}
return false;
}
/**
* Returns a hashcode compatible with equals.
* * @return a hashcode compatible with equals */ public int hashCode() { int total = 0; total += mPattern.hashCode(); total += mTimeZone.hashCode(); total += (mTimeZoneForced ? 1 : 0); total += mLocale.hashCode(); total += (mLocaleForced ? 1 : 0); return total; } /** *Gets a debugging string version of this formatter.
* * @return a debugging string */ public String toString() { return "FastDateFormat[" + mPattern + "]"; } // Serializing //----------------------------------------------------------------------- /** * Create the object after serialization. This implementation reinitializes the * transient properties. * * @param in ObjectInputStream from which the object is being deserialized. * @throws IOException if there is an IO issue. * @throws ClassNotFoundException if a class cannot be found. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); init(); } // Rules //----------------------------------------------------------------------- /** *Inner class defining a rule.
*/ private interface Rule { /** * Returns the estimated lentgh of the result. * * @return the estimated length */ int estimateLength(); /** * Appends the value of the specified calendar to the output buffer based on the rule implementation. * * @param buffer the output buffer * @param calendar calendar to be appended */ void appendTo(StringBuffer buffer, Calendar calendar); } /** *Inner class defining a numeric rule.
*/ private interface NumberRule extends Rule { /** * Appends the specified value to the output buffer based on the rule implementation. * * @param buffer the output buffer * @param value the value to be appended */ void appendTo(StringBuffer buffer, int value); } /** *Inner class to output a constant single character.
*/ private static class CharacterLiteral implements Rule { private final char mValue; /** * Constructs a new instance ofCharacterLiteral
* to hold the specified value.
*
* @param value the character literal
*/
CharacterLiteral(char value) {
mValue = value;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 1;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
buffer.append(mValue);
}
}
/**
* Inner class to output a constant string.
*/ private static class StringLiteral implements Rule { private final String mValue; /** * Constructs a new instance ofStringLiteral
* to hold the specified value.
*
* @param value the string literal
*/
StringLiteral(String value) {
mValue = value;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return mValue.length();
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
buffer.append(mValue);
}
}
/**
* Inner class to output one of a set of values.
*/ private static class TextField implements Rule { private final int mField; private final String[] mValues; /** * Constructs an instance ofTextField
* with the specified field and values.
*
* @param field the field
* @param values the field values
*/
TextField(int field, String[] values) {
mField = field;
mValues = values;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
int max = 0;
for (int i=mValues.length; --i >= 0; ) {
int len = mValues[i].length();
if (len > max) {
max = len;
}
}
return max;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
buffer.append(mValues[calendar.get(mField)]);
}
}
/**
* Inner class to output an unpadded number.
*/ private static class UnpaddedNumberField implements NumberRule { static final UnpaddedNumberField INSTANCE_YEAR = new UnpaddedNumberField(Calendar.YEAR); private final int mField; /** * Constructs an instance ofUnpadedNumberField
with the specified field.
*
* @param field the field
*/
UnpaddedNumberField(int field) {
mField = field;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 4;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(mField));
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
if (value < 10) {
buffer.append((char)(value + '0'));
} else if (value < 100) {
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
} else {
buffer.append(Integer.toString(value));
}
}
}
/**
* Inner class to output an unpadded month.
*/ private static class UnpaddedMonthField implements NumberRule { static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); /** * Constructs an instance ofUnpaddedMonthField
.
*
*/
UnpaddedMonthField() {
super();
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 2;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
if (value < 10) {
buffer.append((char)(value + '0'));
} else {
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
}
}
}
/**
* Inner class to output a padded number.
*/ private static class PaddedNumberField implements NumberRule { private final int mField; private final int mSize; /** * Constructs an instance ofPaddedNumberField
.
*
* @param field the field
* @param size size of the output field
*/
PaddedNumberField(int field, int size) {
if (size < 3) {
// Should use UnpaddedNumberField or TwoDigitNumberField.
throw new IllegalArgumentException();
}
mField = field;
mSize = size;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 4;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(mField));
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
if (value < 100) {
for (int i = mSize; --i >= 2; ) {
buffer.append('0');
}
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
} else {
int digits;
if (value < 1000) {
digits = 3;
} else {
digits = Integer.toString(value).length();
}
for (int i = mSize; --i >= digits; ) {
buffer.append('0');
}
buffer.append(Integer.toString(value));
}
}
}
/**
* Inner class to output a two digit number.
*/ private static class TwoDigitNumberField implements NumberRule { private final int mField; /** * Constructs an instance ofTwoDigitNumberField
with the specified field.
*
* @param field the field
*/
TwoDigitNumberField(int field) {
mField = field;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 2;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(mField));
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
if (value < 100) {
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
} else {
buffer.append(Integer.toString(value));
}
}
}
/**
* Inner class to output a two digit year.
*/ private static class TwoDigitYearField implements NumberRule { static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); /** * Constructs an instance ofTwoDigitYearField
.
*/
TwoDigitYearField() {
super();
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 2;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
}
}
/**
* Inner class to output a two digit month.
*/ private static class TwoDigitMonthField implements NumberRule { static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); /** * Constructs an instance ofTwoDigitMonthField
.
*/
TwoDigitMonthField() {
super();
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 2;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
}
/**
* {@inheritDoc}
*/
public final void appendTo(StringBuffer buffer, int value) {
buffer.append((char)(value / 10 + '0'));
buffer.append((char)(value % 10 + '0'));
}
}
/**
* Inner class to output the twelve hour field.
*/ private static class TwelveHourField implements NumberRule { private final NumberRule mRule; /** * Constructs an instance ofTwelveHourField
with the specified
* NumberRule
.
*
* @param rule the rule
*/
TwelveHourField(NumberRule rule) {
mRule = rule;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return mRule.estimateLength();
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
int value = calendar.get(Calendar.HOUR);
if (value == 0) {
value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
}
mRule.appendTo(buffer, value);
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, int value) {
mRule.appendTo(buffer, value);
}
}
/**
* Inner class to output the twenty four hour field.
*/ private static class TwentyFourHourField implements NumberRule { private final NumberRule mRule; /** * Constructs an instance ofTwentyFourHourField
with the specified
* NumberRule
.
*
* @param rule the rule
*/
TwentyFourHourField(NumberRule rule) {
mRule = rule;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return mRule.estimateLength();
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
int value = calendar.get(Calendar.HOUR_OF_DAY);
if (value == 0) {
value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
}
mRule.appendTo(buffer, value);
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, int value) {
mRule.appendTo(buffer, value);
}
}
/**
* Inner class to output a time zone name.
*/ private static class TimeZoneNameRule implements Rule { private final TimeZone mTimeZone; private final boolean mTimeZoneForced; private final Locale mLocale; private final int mStyle; private final String mStandard; private final String mDaylight; /** * Constructs an instance ofTimeZoneNameRule
with the specified properties.
*
* @param timeZone the time zone
* @param timeZoneForced if true
the time zone is forced into standard and daylight
* @param locale the locale
* @param style the style
*/
TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) {
mTimeZone = timeZone;
mTimeZoneForced = timeZoneForced;
mLocale = locale;
mStyle = style;
if (timeZoneForced) {
mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
} else {
mStandard = null;
mDaylight = null;
}
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
if (mTimeZoneForced) {
return Math.max(mStandard.length(), mDaylight.length());
} else if (mStyle == TimeZone.SHORT) {
return 4;
} else {
return 40;
}
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
if (mTimeZoneForced) {
if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
buffer.append(mDaylight);
} else {
buffer.append(mStandard);
}
} else {
TimeZone timeZone = calendar.getTimeZone();
if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
} else {
buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
}
}
}
}
/**
* Inner class to output a time zone as a number +/-HHMM
* or +/-HH:MM
.
TimeZoneNumberRule
with the specified properties.
*
* @param colon add colon between HH and MM in the output if true
*/
TimeZoneNumberRule(boolean colon) {
mColon = colon;
}
/**
* {@inheritDoc}
*/
public int estimateLength() {
return 5;
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
if (offset < 0) {
buffer.append('-');
offset = -offset;
} else {
buffer.append('+');
}
int hours = offset / (60 * 60 * 1000);
buffer.append((char)(hours / 10 + '0'));
buffer.append((char)(hours % 10 + '0'));
if (mColon) {
buffer.append(':');
}
int minutes = offset / (60 * 1000) - 60 * hours;
buffer.append((char)(minutes / 10 + '0'));
buffer.append((char)(minutes % 10 + '0'));
}
}
// ----------------------------------------------------------------------
/**
* Inner class that acts as a compound key for time zone names.
*/ private static class TimeZoneDisplayKey { private final TimeZone mTimeZone; private final int mStyle; private final Locale mLocale; /** * Constructs an instance ofTimeZoneDisplayKey
with the specified properties.
*
* @param timeZone the time zone
* @param daylight adjust the style for daylight saving time if true
* @param style the timezone style
* @param locale the timezone locale
*/
TimeZoneDisplayKey(TimeZone timeZone,
boolean daylight, int style, Locale locale) {
mTimeZone = timeZone;
if (daylight) {
style |= 0x80000000;
}
mStyle = style;
mLocale = locale;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return mStyle * 31 + mLocale.hashCode();
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof TimeZoneDisplayKey) {
TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
return
mTimeZone.equals(other.mTimeZone) &&
mStyle == other.mStyle &&
mLocale.equals(other.mLocale);
}
return false;
}
}
// ----------------------------------------------------------------------
/**
* Helper class for creating compound objects.
* *One use for this class is to create a hashtable key * out of multiple objects.
*/ private static class Pair { private final Object mObj1; private final Object mObj2; /** * Constructs an instance ofPair
to hold the specified objects.
* @param obj1 one object in the pair
* @param obj2 second object in the pair
*/
public Pair(Object obj1, Object obj2) {
mObj1 = obj1;
mObj2 = obj2;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Pair)) {
return false;
}
Pair key = (Pair)obj;
return
(mObj1 == null ?
key.mObj1 == null : mObj1.equals(key.mObj1)) &&
(mObj2 == null ?
key.mObj2 == null : mObj2.equals(key.mObj2));
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return
(mObj1 == null ? 0 : mObj1.hashCode()) +
(mObj2 == null ? 0 : mObj2.hashCode());
}
/**
* {@inheritDoc}
*/
public String toString() {
return "[" + mObj1 + ':' + mObj2 + ']';
}
}
}