Class FastDateParser
- java.lang.Object
-
- org.apache.logging.log4j.core.util.datetime.FastDateParser
-
- All Implemented Interfaces:
java.io.Serializable,DateParser
public class FastDateParser extends java.lang.Object implements DateParser, java.io.Serializable
FastDateParser is a fast and thread-safe version of
SimpleDateFormat.To obtain a proxy to a FastDateParser, use
FastDateFormat.getInstance(String, TimeZone, Locale)or another variation of the factory methods ofFastDateFormat.Since FastDateParser is thread safe, you can use a static member instance:
private static final DateParser DATE_PARSER = FastDateFormat.getInstance("yyyy-MM-dd");This class can be used as a direct replacement for
SimpleDateFormatin most parsing situations. This class is especially useful in multi-threaded server environments.SimpleDateFormatis not thread-safe in any JDK version, nor will it be as Sun has closed the bug/RFE.Only parsing is supported by this class, but all patterns are compatible with SimpleDateFormat.
The class operates in lenient mode, so for example a time of 90 minutes is treated as 1 hour 30 minutes.
Timing tests indicate this class is as about as fast as SimpleDateFormat in single thread applications and about 25% faster in multi-thread applications.
Copied and modified from Apache Commons Lang.
- Since:
- Apache Commons Lang 3.2
- See Also:
FastDatePrinter, Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classFastDateParser.CaseInsensitiveTextStrategyA strategy that handles a text field in the parsing patternprivate static classFastDateParser.CopyQuotedStrategyA strategy that copies the static or quoted field in the parsing patternprivate static classFastDateParser.ISO8601TimeZoneStrategyprivate static classFastDateParser.NumberStrategyA strategy that handles a number field in the parsing patternprivate static classFastDateParser.PatternStrategyA strategy to parse a single field from the parsing patternprivate static classFastDateParser.StrategyA strategy to parse a single field from the parsing patternprivate static classFastDateParser.StrategyAndWidthHolds strategy and field widthprivate classFastDateParser.StrategyParserParse format into Strategies(package private) static classFastDateParser.TimeZoneStrategyA strategy that handles a timezone field in the parsing pattern
-
Field Summary
-
Constructor Summary
Constructors Modifier Constructor Description protectedFastDateParser(java.lang.String pattern, java.util.TimeZone timeZone, java.util.Locale locale)Constructs a new FastDateParser.protectedFastDateParser(java.lang.String pattern, java.util.TimeZone timeZone, java.util.Locale locale, java.util.Date centuryStart)Constructs a new FastDateParser.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private intadjustYear(int twoDigitYear)Adjust dates to be within appropriate centuryprivate static java.util.Map<java.lang.String,java.lang.Integer>appendDisplayNames(java.util.Calendar cal, java.util.Locale locale, int field, java.lang.StringBuilder regex)Get the short and long values displayed for a fieldbooleanequals(java.lang.Object obj)Compare another object for equality with this object.private static java.util.concurrent.ConcurrentMap<java.util.Locale,FastDateParser.Strategy>getCache(int field)Get a cache of Strategies for a particular fieldjava.util.LocalegetLocale()Gets the locale used by this parser.private FastDateParser.StrategygetLocaleSpecificStrategy(int field, java.util.Calendar definingCalendar)Construct a Strategy that parses a Text fieldjava.lang.StringgetPattern()Gets the pattern used by this parser.private FastDateParser.StrategygetStrategy(char f, int width, java.util.Calendar definingCalendar)Obtain a Strategy given a field from a SimpleDateFormat patternjava.util.TimeZonegetTimeZone()Gets the time zone used by this parser.inthashCode()Return a hash code compatible with equals.private voidinit(java.util.Calendar definingCalendar)Initialize derived fields from defining fields.private static booleanisFormatLetter(char c)java.util.Dateparse(java.lang.String source)Equivalent to DateFormat.parse(String).java.util.Dateparse(java.lang.String source, java.text.ParsePosition pos)This implementation updates the ParsePosition if the parse succeeds.booleanparse(java.lang.String source, java.text.ParsePosition pos, java.util.Calendar calendar)Parse a formatted date string according to the format.java.lang.ObjectparseObject(java.lang.String source)Parses text from a string to produce a Date.java.lang.ObjectparseObject(java.lang.String source, java.text.ParsePosition pos)Parses a date/time string according to the given parse position.private voidreadObject(java.io.ObjectInputStream in)Create the object after serialization.private static java.lang.StringBuildersimpleQuote(java.lang.StringBuilder sb, java.lang.String value)java.lang.StringtoString()Get a string version of this formatter.
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
Required for serialization support.- See Also:
Serializable, Constant Field Values
-
JAPANESE_IMPERIAL
static final java.util.Locale JAPANESE_IMPERIAL
-
pattern
private final java.lang.String pattern
-
timeZone
private final java.util.TimeZone timeZone
-
locale
private final java.util.Locale locale
-
century
private final int century
-
startYear
private final int startYear
-
patterns
private transient java.util.List<FastDateParser.StrategyAndWidth> patterns
-
LONGER_FIRST_LOWERCASE
private static final java.util.Comparator<java.lang.String> LONGER_FIRST_LOWERCASE
-
caches
private static final java.util.concurrent.ConcurrentMap<java.util.Locale,FastDateParser.Strategy>[] caches
-
ABBREVIATED_YEAR_STRATEGY
private static final FastDateParser.Strategy ABBREVIATED_YEAR_STRATEGY
-
NUMBER_MONTH_STRATEGY
private static final FastDateParser.Strategy NUMBER_MONTH_STRATEGY
-
LITERAL_YEAR_STRATEGY
private static final FastDateParser.Strategy LITERAL_YEAR_STRATEGY
-
WEEK_OF_YEAR_STRATEGY
private static final FastDateParser.Strategy WEEK_OF_YEAR_STRATEGY
-
WEEK_OF_MONTH_STRATEGY
private static final FastDateParser.Strategy WEEK_OF_MONTH_STRATEGY
-
DAY_OF_YEAR_STRATEGY
private static final FastDateParser.Strategy DAY_OF_YEAR_STRATEGY
-
DAY_OF_MONTH_STRATEGY
private static final FastDateParser.Strategy DAY_OF_MONTH_STRATEGY
-
DAY_OF_WEEK_STRATEGY
private static final FastDateParser.Strategy DAY_OF_WEEK_STRATEGY
-
DAY_OF_WEEK_IN_MONTH_STRATEGY
private static final FastDateParser.Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY
-
HOUR_OF_DAY_STRATEGY
private static final FastDateParser.Strategy HOUR_OF_DAY_STRATEGY
-
HOUR24_OF_DAY_STRATEGY
private static final FastDateParser.Strategy HOUR24_OF_DAY_STRATEGY
-
HOUR12_STRATEGY
private static final FastDateParser.Strategy HOUR12_STRATEGY
-
HOUR_STRATEGY
private static final FastDateParser.Strategy HOUR_STRATEGY
-
MINUTE_STRATEGY
private static final FastDateParser.Strategy MINUTE_STRATEGY
-
SECOND_STRATEGY
private static final FastDateParser.Strategy SECOND_STRATEGY
-
MILLISECOND_STRATEGY
private static final FastDateParser.Strategy MILLISECOND_STRATEGY
-
-
Constructor Detail
-
FastDateParser
protected FastDateParser(java.lang.String pattern, java.util.TimeZone timeZone, java.util.Locale locale)Constructs a new FastDateParser.
UseFastDateFormat.getInstance(String, TimeZone, Locale)or another variation of the factory methods ofFastDateFormatto get a cached FastDateParser instance.- Parameters:
pattern- non-nullSimpleDateFormatcompatible patterntimeZone- non-null time zone to uselocale- non-null locale
-
FastDateParser
protected FastDateParser(java.lang.String pattern, java.util.TimeZone timeZone, java.util.Locale locale, java.util.Date centuryStart)Constructs a new FastDateParser.
- Parameters:
pattern- non-nullSimpleDateFormatcompatible patterntimeZone- non-null time zone to uselocale- non-null localecenturyStart- The start of the century for 2 digit year parsing- Since:
- 3.5
-
-
Method Detail
-
init
private void init(java.util.Calendar definingCalendar)
Initialize derived fields from defining fields. This is called from constructor and from readObject (de-serialization)- Parameters:
definingCalendar- theCalendarinstance used to initialize this FastDateParser
-
isFormatLetter
private static boolean isFormatLetter(char c)
-
getPattern
public java.lang.String getPattern()
Description copied from interface:DateParserGets the pattern used by this parser.
- Specified by:
getPatternin interfaceDateParser- Returns:
- the pattern,
SimpleDateFormatcompatible
-
getTimeZone
public java.util.TimeZone getTimeZone()
Description copied from interface:DateParserGets the time zone used by this parser.
The default
TimeZoneused to create aDatewhen theTimeZoneis not specified by the format pattern.- Specified by:
getTimeZonein interfaceDateParser- Returns:
- the time zone
-
getLocale
public java.util.Locale getLocale()
Description copied from interface:DateParserGets the locale used by this parser.
- Specified by:
getLocalein interfaceDateParser- Returns:
- the locale
-
equals
public boolean equals(java.lang.Object obj)
Compare another object for equality with this object.
- Overrides:
equalsin classjava.lang.Object- Parameters:
obj- the object to compare to- Returns:
trueif equal to this instance
-
hashCode
public int hashCode()
Return a hash code compatible with equals.
- Overrides:
hashCodein classjava.lang.Object- Returns:
- a hash code compatible with equals
-
toString
public java.lang.String toString()
Get a string version of this formatter.
- Overrides:
toStringin classjava.lang.Object- Returns:
- a debugging string
-
readObject
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundExceptionCreate the object after serialization. This implementation reinitializes the transient properties.- Parameters:
in- ObjectInputStream from which the object is being deserialized.- Throws:
java.io.IOException- if there is an IO issue.java.lang.ClassNotFoundException- if a class cannot be found.
-
parseObject
public java.lang.Object parseObject(java.lang.String source) throws java.text.ParseExceptionDescription copied from interface:DateParserParses text from a string to produce a Date.- Specified by:
parseObjectin interfaceDateParser- Parameters:
source- AStringwhose beginning should be parsed.- Returns:
- a
java.util.Dateobject - Throws:
java.text.ParseException- if the beginning of the specified string cannot be parsed.- See Also:
Format.parseObject(String)
-
parse
public java.util.Date parse(java.lang.String source) throws java.text.ParseExceptionDescription copied from interface:DateParserEquivalent to DateFormat.parse(String). SeeDateFormat.parse(String)for more information.- Specified by:
parsein interfaceDateParser- Parameters:
source- AStringwhose beginning should be parsed.- Returns:
- A
Dateparsed from the string - Throws:
java.text.ParseException- if the beginning of the specified string cannot be parsed.
-
parseObject
public java.lang.Object parseObject(java.lang.String source, java.text.ParsePosition pos)Description copied from interface:DateParserParses a date/time string according to the given parse position.- Specified by:
parseObjectin interfaceDateParser- Parameters:
source- AStringwhose beginning should be parsed.pos- the parse position- Returns:
- a
java.util.Dateobject - See Also:
DateFormat.parseObject(String, ParsePosition)
-
parse
public java.util.Date parse(java.lang.String source, java.text.ParsePosition pos)This implementation updates the ParsePosition if the parse succeeds. However, it sets the error index to the position before the failed field unlike the methodSimpleDateFormat.parse(String, ParsePosition)which sets the error index to after the failed field.To determine if the parse has succeeded, the caller must check if the current parse position given by
ParsePosition.getIndex()has been updated. If the input buffer has been fully parsed, then the index will point to just after the end of the input buffer.- Specified by:
parsein interfaceDateParser- Parameters:
source- AString, part of which should be parsed.pos- AParsePositionobject with index and error index information as described above.- Returns:
- A
Dateparsed from the string. In case of error, returns null. - See Also:
DateParser.parse(java.lang.String, java.text.ParsePosition)
-
parse
public boolean parse(java.lang.String source, java.text.ParsePosition pos, java.util.Calendar calendar)Parse a formatted date string according to the format. Updates the Calendar with parsed fields. Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to the offset of the source text which does not match the supplied format.- Specified by:
parsein interfaceDateParser- Parameters:
source- The text to parse.pos- On input, the position in the source to start parsing, on output, updated position.calendar- The calendar into which to set parsed fields.- Returns:
- true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated)
- Throws:
java.lang.IllegalArgumentException- when Calendar has been set to be not lenient, and a parsed field is out of range.
-
simpleQuote
private static java.lang.StringBuilder simpleQuote(java.lang.StringBuilder sb, java.lang.String value)
-
appendDisplayNames
private static java.util.Map<java.lang.String,java.lang.Integer> appendDisplayNames(java.util.Calendar cal, java.util.Locale locale, int field, java.lang.StringBuilder regex)Get the short and long values displayed for a field- Parameters:
cal- The calendar to obtain the short and long valueslocale- The locale of display namesfield- The field of interestregex- The regular expression to build- Returns:
- The map of string display names to field values
-
adjustYear
private int adjustYear(int twoDigitYear)
Adjust dates to be within appropriate century- Parameters:
twoDigitYear- The year to adjust- Returns:
- A value between centuryStart(inclusive) to centuryStart+100(exclusive)
-
getStrategy
private FastDateParser.Strategy getStrategy(char f, int width, java.util.Calendar definingCalendar)
Obtain a Strategy given a field from a SimpleDateFormat pattern- Parameters:
formatField- A sub-sequence of the SimpleDateFormat patterndefiningCalendar- The calendar to obtain the short and long values- Returns:
- The Strategy that will handle parsing for the field
-
getCache
private static java.util.concurrent.ConcurrentMap<java.util.Locale,FastDateParser.Strategy> getCache(int field)
Get a cache of Strategies for a particular field- Parameters:
field- The Calendar field- Returns:
- a cache of Locale to Strategy
-
getLocaleSpecificStrategy
private FastDateParser.Strategy getLocaleSpecificStrategy(int field, java.util.Calendar definingCalendar)
Construct a Strategy that parses a Text field- Parameters:
field- The Calendar fielddefiningCalendar- The calendar to obtain the short and long values- Returns:
- a TextStrategy for the field and Locale
-
-