/* * 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. */ package org.apache.commons.lang3.time; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.exception.ExceptionUtils; /** * FastDatePrinter is a fast and thread-safe version of * {@link java.text.SimpleDateFormat}. * *
To obtain a FastDatePrinter, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} * or another variation of the factory methods of {@link FastDateFormat}.
* *Since FastDatePrinter is thread safe, you can use a static member instance:
* {@code * private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd"); * } * *This class can be used as a direct replacement to * {@link SimpleDateFormat} in most formatting situations. * This class is especially useful in multi-threaded server environments. * {@link SimpleDateFormat} is not thread-safe in any JDK version, * nor will it be as Sun have closed the bug/RFE. *
* *Only formatting is supported by this class, but all patterns are compatible with * SimpleDateFormat (except time zones and some year patterns - see below).
* *Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). * This pattern letter can be used here (on all JDK versions).
* *In addition, the pattern {@code 'ZZ'} has been made to represent * ISO 8601 extended format time zones (eg. {@code +08:00} or {@code -11:00}). * This introduces a minor incompatibility with Java 1.4, but at a gain of * useful functionality.
* *Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}. * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using * one of the {@code 'X'} formats is recommended. * *
Javadoc cites for the year pattern: For formatting, if the number of * pattern letters is 2, the year is truncated to 2 digits; otherwise it is * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or * 'YYY' will be formatted as '2003', while it was '03' in former Java * versions. FastDatePrinter implements the behavior of Java 7.
* * @since 3.2 * @see FastDateParser */ public class FastDatePrinter implements DatePrinter, Serializable { // A lot of the speed in this class comes from caching, but some comes // from the special int to StringBuffer conversion. // // The following produces a padded 2-digit number: // buffer.append((char)(value / 10 + '0')); // buffer.append((char)(value % 10 + '0')); // // Note that the fastest append to StringBuffer is a single char (used here). // Note that Integer.toString() is not called, the conversion is simply // taking the value and adding (mathematically) the ASCII value for '0'. // So, don't change this code! It works and is very fast. /** * Inner class to output a constant single character. */ private static class CharacterLiteral implements Rule { private final char value; /** * Constructs a new instance of {@link CharacterLiteral} * to hold the specified value. * * @param value the character literal */ CharacterLiteral(final char value) { this.value = value; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(value); } /** * {@inheritDoc} */ @Override public int estimateLength() { return 1; } } /** * Inner class to output the numeric day in week. */ private static class DayInWeekField implements NumberRule { private final NumberRule rule; DayInWeekField(final NumberRule rule) { this.rule = rule; } @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { final int value = calendar.get(Calendar.DAY_OF_WEEK); rule.appendTo(buffer, value == Calendar.SUNDAY ? 7 : value - 1); } @Override public void appendTo(final Appendable buffer, final int value) throws IOException { rule.appendTo(buffer, value); } @Override public int estimateLength() { return rule.estimateLength(); } } /** * Inner class to output a time zone as a number {@code +/-HHMM} * or {@code +/-HH:MM}. */ private static class Iso8601_Rule implements Rule { // Sign TwoDigitHours or Z static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); // Sign TwoDigitHours Minutes or Z static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); // Sign TwoDigitHours : Minutes or Z static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); /** * Factory method for Iso8601_Rules. * * @param tokenLen a token indicating the length of the TimeZone String to be formatted. * @return an Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such * rule exists, an IllegalArgumentException will be thrown. */ static Iso8601_Rule getRule(final int tokenLen) { switch (tokenLen) { case 1: return ISO8601_HOURS; case 2: return ISO8601_HOURS_MINUTES; case 3: return ISO8601_HOURS_COLON_MINUTES; default: throw new IllegalArgumentException("invalid number of X"); } } private final int length; /** * Constructs an instance of {@code Iso8601_Rule} with the specified properties. * * @param length The number of characters in output (unless Z is output) */ Iso8601_Rule(final int length) { this.length = length; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); if (offset == 0) { buffer.append("Z"); return; } if (offset < 0) { buffer.append('-'); offset = -offset; } else { buffer.append('+'); } final int hours = offset / (60 * 60 * 1000); appendDigits(buffer, hours); if (length < 5) { return; } if (length == 6) { buffer.append(':'); } final int minutes = offset / (60 * 1000) - 60 * hours; appendDigits(buffer, minutes); } /** * {@inheritDoc} */ @Override public int estimateLength() { return length; } } /** * 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 * @throws IOException if an I/O error occurs. */ void appendTo(Appendable buffer, int value) throws IOException; } /** * Inner class to output a padded number. */ private static final class PaddedNumberField implements NumberRule { // Note: This is final to avoid Spotbugs CT_CONSTRUCTOR_THROW private final int field; private final int size; /** * Constructs an instance of {@link PaddedNumberField}. * * @param field the field * @param size size of the output field */ PaddedNumberField(final int field, final int size) { if (size < 3) { // Should use UnpaddedNumberField or TwoDigitNumberField. throw new IllegalArgumentException(); } this.field = field; this.size = size; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(field)); } /** * {@inheritDoc} */ @Override public /* final */ void appendTo(final Appendable buffer, final int value) throws IOException { // Checkstyle complains about redundant qualifier appendFullDigits(buffer, value, size); } /** * {@inheritDoc} */ @Override public int estimateLength() { return size; } } // Rules /** * Inner class defining a rule. */ private interface Rule { /** * Appends the value of the specified calendar to the output buffer based on the rule implementation. * * @param buf the output buffer * @param calendar calendar to be appended * @throws IOException if an I/O error occurs. */ void appendTo(Appendable buf, Calendar calendar) throws IOException; /** * Returns the estimated length of the result. * * @return the estimated length */ int estimateLength(); } /** * Inner class to output a constant string. */ private static class StringLiteral implements Rule { private final String value; /** * Constructs a new instance of {@link StringLiteral} * to hold the specified value. * * @param value the string literal */ StringLiteral(final String value) { this.value = value; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(value); } /** * {@inheritDoc} */ @Override public int estimateLength() { return value.length(); } } /** * Inner class to output one of a set of values. */ private static class TextField implements Rule { private final int field; private final String[] values; /** * Constructs an instance of {@link TextField} * with the specified field and values. * * @param field the field * @param values the field values */ TextField(final int field, final String[] values) { this.field = field; this.values = values; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(values[calendar.get(field)]); } /** * {@inheritDoc} */ @Override public int estimateLength() { int max = 0; for (int i = values.length; --i >= 0;) { final int len = values[i].length(); if (len > max) { max = len; } } return max; } } /** * Inner class that acts as a compound key for time zone names. */ private static class TimeZoneDisplayKey { private final TimeZone timeZone; private final int style; private final Locale locale; /** * Constructs an instance of {@link TimeZoneDisplayKey} with the specified properties. * * @param timeZone the time zone * @param daylight adjust the style for daylight saving time if {@code true} * @param style the time zone style * @param locale the time zone locale */ TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, final int style, final Locale locale) { this.timeZone = timeZone; if (daylight) { this.style = style | 0x80000000; } else { this.style = style; } this.locale = LocaleUtils.toLocale(locale); } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof TimeZoneDisplayKey) { final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; return timeZone.equals(other.timeZone) && style == other.style && locale.equals(other.locale); } return false; } /** * {@inheritDoc} */ @Override public int hashCode() { return (style * 31 + locale.hashCode() ) * 31 + timeZone.hashCode(); } } /** * Inner class to output a time zone name. */ private static class TimeZoneNameRule implements Rule { private final Locale locale; private final int style; private final String standard; private final String daylight; /** * Constructs an instance of {@link TimeZoneNameRule} with the specified properties. * * @param timeZone the time zone * @param locale the locale * @param style the style */ TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { this.locale = LocaleUtils.toLocale(locale); this.style = style; this.standard = getTimeZoneDisplay(timeZone, false, style, locale); this.daylight = getTimeZoneDisplay(timeZone, true, style, locale); } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { final TimeZone zone = calendar.getTimeZone(); final boolean daylight = calendar.get(Calendar.DST_OFFSET) != 0; buffer.append(getTimeZoneDisplay(zone, daylight, style, locale)); } /** * {@inheritDoc} */ @Override public int estimateLength() { // We have no access to the Calendar object that will be passed to // appendTo so base estimate on the TimeZone passed to the // constructor return Math.max(standard.length(), daylight.length()); } } /** * Inner class to output a time zone as a number {@code +/-HHMM} * or {@code +/-HH:MM}. */ private static class TimeZoneNumberRule implements Rule { static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); private final boolean colon; /** * Constructs an instance of {@link TimeZoneNumberRule} with the specified properties. * * @param colon add colon between HH and MM in the output if {@code true} */ TimeZoneNumberRule(final boolean colon) { this.colon = colon; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); if (offset < 0) { buffer.append('-'); offset = -offset; } else { buffer.append('+'); } final int hours = offset / (60 * 60 * 1000); appendDigits(buffer, hours); if (colon) { buffer.append(':'); } final int minutes = offset / (60 * 1000) - 60 * hours; appendDigits(buffer, minutes); } /** * {@inheritDoc} */ @Override public int estimateLength() { return 5; } } /** * Inner class to output the twelve hour field. */ private static class TwelveHourField implements NumberRule { private final NumberRule rule; /** * Constructs an instance of {@link TwelveHourField} with the specified * {@link NumberRule}. * * @param rule the rule */ TwelveHourField(final NumberRule rule) { this.rule = rule; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int value = calendar.get(Calendar.HOUR); if (value == 0) { value = calendar.getLeastMaximum(Calendar.HOUR) + 1; } rule.appendTo(buffer, value); } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final int value) throws IOException { rule.appendTo(buffer, value); } /** * {@inheritDoc} */ @Override public int estimateLength() { return rule.estimateLength(); } } /** * Inner class to output the twenty four hour field. */ private static class TwentyFourHourField implements NumberRule { private final NumberRule rule; /** * Constructs an instance of {@link TwentyFourHourField} with the specified * {@link NumberRule}. * * @param rule the rule */ TwentyFourHourField(final NumberRule rule) { this.rule = rule; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int value = calendar.get(Calendar.HOUR_OF_DAY); if (value == 0) { value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; } rule.appendTo(buffer, value); } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final int value) throws IOException { rule.appendTo(buffer, value); } /** * {@inheritDoc} */ @Override public int estimateLength() { return rule.estimateLength(); } } /** * Inner class to output a two digit month. */ private static class TwoDigitMonthField implements NumberRule { static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); /** * Constructs an instance of {@link TwoDigitMonthField}. */ TwoDigitMonthField() { } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } /** * {@inheritDoc} */ @Override public final void appendTo(final Appendable buffer, final int value) throws IOException { appendDigits(buffer, value); } /** * {@inheritDoc} */ @Override public int estimateLength() { return 2; } } /** * Inner class to output a two digit number. */ private static class TwoDigitNumberField implements NumberRule { private final int field; /** * Constructs an instance of {@link TwoDigitNumberField} with the specified field. * * @param field the field */ TwoDigitNumberField(final int field) { this.field = field; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(field)); } /** * {@inheritDoc} */ @Override public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 100) { appendDigits(buffer, value); } else { appendFullDigits(buffer, value, 2); } } /** * {@inheritDoc} */ @Override public int estimateLength() { return 2; } } /** * Inner class to output a two digit year. */ private static class TwoDigitYearField implements NumberRule { static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); /** * Constructs an instance of {@link TwoDigitYearField}. */ TwoDigitYearField() { } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.YEAR) % 100); } /** * {@inheritDoc} */ @Override public final void appendTo(final Appendable buffer, final int value) throws IOException { appendDigits(buffer, value % 100); } /** * {@inheritDoc} */ @Override public int estimateLength() { return 2; } } /** * Inner class to output an unpadded month. */ private static class UnpaddedMonthField implements NumberRule { static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); /** * Constructs an instance of {@link UnpaddedMonthField}. */ UnpaddedMonthField() { } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } /** * {@inheritDoc} */ @Override public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 10) { buffer.append((char) (value + '0')); } else { appendDigits(buffer, value); } } /** * {@inheritDoc} */ @Override public int estimateLength() { return 2; } } /** * Inner class to output an unpadded number. */ private static class UnpaddedNumberField implements NumberRule { private final int field; /** * Constructs an instance of {@link UnpaddedNumberField} with the specified field. * * @param field the field */ UnpaddedNumberField(final int field) { this.field = field; } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(field)); } /** * {@inheritDoc} */ @Override public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 10) { buffer.append((char) (value + '0')); } else if (value < 100) { appendDigits(buffer, value); } else { appendFullDigits(buffer, value, 1); } } /** * {@inheritDoc} */ @Override public int estimateLength() { return 4; } } /** * Inner class to output the numeric day in week. */ private static class WeekYear implements NumberRule { private final NumberRule rule; WeekYear(final NumberRule rule) { this.rule = rule; } @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { rule.appendTo(buffer, calendar.getWeekYear()); } @Override public void appendTo(final Appendable buffer, final int value) throws IOException { rule.appendTo(buffer, value); } @Override public int estimateLength() { return rule.estimateLength(); } } /** Empty array. */ private static final Rule[] EMPTY_RULE_ARRAY = {}; /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * FULL locale dependent date or time style. */ public static final int FULL = DateFormat.FULL; /** * LONG locale dependent date or time style. */ public static final int LONG = DateFormat.LONG; /** * MEDIUM locale dependent date or time style. */ public static final int MEDIUM = DateFormat.MEDIUM; /** * SHORT locale dependent date or time style. */ public static final int SHORT = DateFormat.SHORT; private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3 private static final ConcurrentMapThe actual formatted length will almost always be less than or * equal to this amount.
* * @return the maximum formatted length */ public int getMaxLengthEstimate() { return maxLengthEstimate; } // Accessors /* (non-Javadoc) * @see org.apache.commons.lang3.time.DatePrinter#getPattern() */ @Override public String getPattern() { return pattern; } /* (non-Javadoc) * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() */ @Override public TimeZone getTimeZone() { return timeZone; } /** * Returns a hash code compatible with equals. * * @return a hash code compatible with equals */ @Override public int hashCode() { return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); } /** * Initializes the instance for first use. */ private void init() { final List