Most visited

Recently visited

Added in API level 24

DateTimePatternGenerator

public class DateTimePatternGenerator
extends Object implements Freezable<DateTimePatternGenerator>, Cloneable

java.lang.Object
   ↳ android.icu.text.DateTimePatternGenerator


This class provides flexible generation of date format patterns, like "yy-MM-dd". The user can build up the generator by adding successive patterns. Once that is done, a query can be made using a "skeleton", which is a pattern which just includes the desired fields and lengths. The generator will return the "best fit" pattern corresponding to that skeleton.

The main method people will use is getBestPattern(String skeleton), since normally this class is pre-built with data from a particular locale. However, generators can be built directly from other data as well.

Summary

Nested classes

class DateTimePatternGenerator.PatternInfo

PatternInfo supplies output parameters for addPattern(...). 

Constants

int DAY

int DAYPERIOD

int DAY_OF_WEEK_IN_MONTH

int DAY_OF_YEAR

int ERA

int FRACTIONAL_SECOND

int HOUR

int MATCH_ALL_FIELDS_LENGTH

Option mask for forcing the width of all date and time fields.

int MATCH_HOUR_FIELD_LENGTH

Option mask for forcing the width of hour field.

int MATCH_NO_OPTIONS

Default option mask used for getBestPattern(String, int) and replaceFieldTypes(String, String, int).

int MINUTE

int MONTH

int QUARTER

int SECOND

int WEEKDAY

int WEEK_OF_MONTH

int WEEK_OF_YEAR

int YEAR

int ZONE

Protected constructors

DateTimePatternGenerator()

Only for use by subclasses

Public methods

DateTimePatternGenerator addPattern(String pattern, boolean override, DateTimePatternGenerator.PatternInfo returnInfo)

Adds a pattern to the generator.

Object clone()

Returns a copy of this DateTimePatternGenerator object.

DateTimePatternGenerator cloneAsThawed()

Provides for the clone operation.

DateTimePatternGenerator freeze()

Freezes the object.

String getAppendItemFormat(int field)

Getter corresponding to setAppendItemFormats.

String getAppendItemName(int field)

Getter corresponding to setAppendItemNames.

String getBaseSkeleton(String pattern)

Utility to return a unique base skeleton from a given pattern.

Set<String> getBaseSkeletons(Set<String> result)

Return a list of all the base skeletons (in canonical form) from this class

String getBestPattern(String skeleton, int options)

Return the best pattern matching the input skeleton.

String getBestPattern(String skeleton)

Return the best pattern matching the input skeleton.

String getDateTimeFormat()

Getter corresponding to setDateTimeFormat.

String getDecimal()

Getter corresponding to setDecimal.

static DateTimePatternGenerator getEmptyInstance()

Create empty generator, to be constructed with addPattern(...) etc.

static DateTimePatternGenerator getInstance()

Construct a flexible generator according to data for the default FORMAT locale.

static DateTimePatternGenerator getInstance(Locale locale)

Construct a flexible generator according to data for a given locale.

static DateTimePatternGenerator getInstance(ULocale uLocale)

Construct a flexible generator according to data for a given locale.

String getSkeleton(String pattern)

Utility to return a unique skeleton from a given pattern.

Map<StringString> getSkeletons(Map<StringString> result)

Return a list of all the skeletons (in canonical form) from this class, and the patterns that they map to.

boolean isFrozen()

Determines whether the object has been frozen or not.

String replaceFieldTypes(String pattern, String skeleton)

Adjusts the field types (width and subtype) of a pattern to match what is in a skeleton.

String replaceFieldTypes(String pattern, String skeleton, int options)

Adjusts the field types (width and subtype) of a pattern to match what is in a skeleton.

void setAppendItemFormat(int field, String value)

An AppendItem format is a pattern used to append a field if there is no good match.

void setAppendItemName(int field, String value)

Sets the names of fields, eg "era" in English for ERA.

void setDateTimeFormat(String dateTimeFormat)

The date time format is a message format pattern used to compose date and time patterns.

void setDecimal(String decimal)

The decimal value is used in formatting fractions of seconds.

Inherited methods

From class java.lang.Object
From interface android.icu.util.Freezable

Constants

DAY

Added in API level 24
int DAY

Constant Value: 7 (0x00000007)

DAYPERIOD

Added in API level 24
int DAYPERIOD

Constant Value: 10 (0x0000000a)

DAY_OF_WEEK_IN_MONTH

Added in API level 24
int DAY_OF_WEEK_IN_MONTH

Constant Value: 9 (0x00000009)

DAY_OF_YEAR

Added in API level 24
int DAY_OF_YEAR

Constant Value: 8 (0x00000008)

ERA

Added in API level 24
int ERA

Constant Value: 0 (0x00000000)

FRACTIONAL_SECOND

Added in API level 24
int FRACTIONAL_SECOND

Constant Value: 14 (0x0000000e)

HOUR

Added in API level 24
int HOUR

Constant Value: 11 (0x0000000b)

MATCH_ALL_FIELDS_LENGTH

Added in API level 24
int MATCH_ALL_FIELDS_LENGTH

Option mask for forcing the width of all date and time fields.

See also:

Constant Value: 65535 (0x0000ffff)

MATCH_HOUR_FIELD_LENGTH

Added in API level 24
int MATCH_HOUR_FIELD_LENGTH

Option mask for forcing the width of hour field.

See also:

Constant Value: 2048 (0x00000800)

MATCH_NO_OPTIONS

Added in API level 24
int MATCH_NO_OPTIONS

Default option mask used for getBestPattern(String, int) and replaceFieldTypes(String, String, int).

See also:

Constant Value: 0 (0x00000000)

MINUTE

Added in API level 24
int MINUTE

Constant Value: 12 (0x0000000c)

MONTH

Added in API level 24
int MONTH

Constant Value: 3 (0x00000003)

QUARTER

Added in API level 24
int QUARTER

Constant Value: 2 (0x00000002)

SECOND

Added in API level 24
int SECOND

Constant Value: 13 (0x0000000d)

WEEKDAY

Added in API level 24
int WEEKDAY

Constant Value: 6 (0x00000006)

WEEK_OF_MONTH

Added in API level 24
int WEEK_OF_MONTH

Constant Value: 5 (0x00000005)

WEEK_OF_YEAR

Added in API level 24
int WEEK_OF_YEAR

Constant Value: 4 (0x00000004)

YEAR

Added in API level 24
int YEAR

Constant Value: 1 (0x00000001)

ZONE

Added in API level 24
int ZONE

Constant Value: 15 (0x0000000f)

Protected constructors

DateTimePatternGenerator

Added in API level 24
DateTimePatternGenerator ()

Only for use by subclasses

Public methods

addPattern

Added in API level 24
DateTimePatternGenerator addPattern (String pattern, 
                boolean override, 
                DateTimePatternGenerator.PatternInfo returnInfo)

Adds a pattern to the generator. If the pattern has the same skeleton as an existing pattern, and the override parameter is set, then the previous value is overridden. Otherwise, the previous value is retained. In either case, the conflicting information is returned in PatternInfo.

Note that single-field patterns (like "MMM") are automatically added, and don't need to be added explicitly! *

Example code:

Date date= new GregorianCalendar(1999,9,13,23,58,59).getTime();
ULocale locale = ULocale.FRANCE;
// Create an DateTimePatternGenerator instance for the given locale
DateTimePatternGenerator gen = DateTimePatternGenerator.getInstance(locale);
SimpleDateFormat format = new SimpleDateFormat(gen.getBestPattern("MMMMddHmm"), locale);
DateTimePatternGenerator.PatternInfo returnInfo = new DateTimePatternGenerator.PatternInfo();
// Add '. von' to the existing pattern
gen.addPattern("dd'. von' MMMM", true, returnInfo);
// Apply the new pattern
format.applyPattern(gen.getBestPattern("MMMMddHmm"));
System.out.println("New Pattern for FRENCH: "+format.toPattern());
System.out.println("Date Time in new Pattern: "+format.format(date));

/** output of the sample code:
**************************************************************************************************
 New Pattern for FRENCH: dd. 'von' MMMM HH:mm
 Date Time in new Pattern: 13. von octobre 23:58

*************************************************************************************************/

Parameters
pattern String: Pattern to add.
override boolean: When existing values are to be overridden use true, otherwise use false.
returnInfo DateTimePatternGenerator.PatternInfo: Returned information.
Returns
DateTimePatternGenerator

clone

Added in API level 24
Object clone ()

Returns a copy of this DateTimePatternGenerator object.

Returns
Object A copy of this DateTimePatternGenerator object.

cloneAsThawed

Added in API level 24
DateTimePatternGenerator cloneAsThawed ()

Provides for the clone operation. Any clone is initially unfrozen.

Returns
DateTimePatternGenerator

freeze

Added in API level 24
DateTimePatternGenerator freeze ()

Freezes the object.

Returns
DateTimePatternGenerator the object itself.

getAppendItemFormat

Added in API level 24
String getAppendItemFormat (int field)

Getter corresponding to setAppendItemFormats. Values below 0 or at or above TYPE_LIMIT are illegal arguments.

Parameters
field int: The index to retrieve the append item formats.
Returns
String append pattern for field

getAppendItemName

Added in API level 24
String getAppendItemName (int field)

Getter corresponding to setAppendItemNames. Values below 0 or at or above TYPE_LIMIT are illegal arguments.

Parameters
field int: The index to get the append item name.
Returns
String name for field

getBaseSkeleton

Added in API level 24
String getBaseSkeleton (String pattern)

Utility to return a unique base skeleton from a given pattern. This is the same as the skeleton, except that differences in length are minimized so as to only preserve the difference between string and numeric form. So for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" (notice the single d).

Parameters
pattern String: Input pattern, such as "dd/MMM"
Returns
String skeleton, such as "MMMdd"

getBaseSkeletons

Added in API level 24
Set<String> getBaseSkeletons (Set<String> result)

Return a list of all the base skeletons (in canonical form) from this class

Parameters
result Set
Returns
Set<String>

getBestPattern

Added in API level 24
String getBestPattern (String skeleton, 
                int options)

Return the best pattern matching the input skeleton. It is guaranteed to have all of the fields in the skeleton.

Parameters
skeleton String: The skeleton is a pattern containing only the variable fields. For example, "MMMdd" and "mmhh" are skeletons.
options int: MATCH_xxx options for forcing the length of specified fields in the returned pattern to match those in the skeleton (when this would not happen otherwise). For default behavior, use MATCH_NO_OPTIONS.
Returns
String Best pattern matching the input skeleton (and options).

getBestPattern

Added in API level 24
String getBestPattern (String skeleton)

Return the best pattern matching the input skeleton. It is guaranteed to have all of the fields in the skeleton.

Example code:

final String[] skeletons = {
        "yQQQQ", // year + full name of quarter, i.e., 4th quarter 1999
        "yMMMM", // year + full name of month, i.e., October 1999
        "MMMMd", // full name of month + day of the month, i.e., October 25
        "hhmm",  // 12-hour-cycle format, i.e., 1:32 PM
        "jjmm"   // preferred hour format for the given locale, i.e., 24-hour-cycle format for fr_FR
        };
final ULocale[] locales = {
        new ULocale ("en_US"),
        new ULocale ("fr_FR"),
        new ULocale ("zh_CN"),
        };
DateTimePatternGenerator dtfg = null;
Date date= new GregorianCalendar(1999,9,13,23,58,59).getTime();
System.out.printf("%-20s%-35s%-35s%-35s\n\n", "Skeleton", "en_US", "fr_FR","zh_CN");
for (String skeleton:skeletons) {
     System.out.printf("%-20s", skeleton);
    for (ULocale locale:locales) {
        // create a DateTimePatternGenerator instance for given locale
        dtfg = DateTimePatternGenerator.getInstance(locale);
        // use getBestPattern method to get the best pattern for the given skeleton
        String pattern = dtfg.getBestPattern(skeleton);
        // Constructs a SimpleDateFormat with the best pattern generated above and the given locale
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
        // Get the format of the given date
        System.out.printf("%-35s",sdf.format(date));
    }
    System.out.println("\n");
}
/** output of the sample code:
 *************************************************************************************************************
   Skeleton            en_US                              fr_FR                              zh_CN

   yQQQQ               4th quarter 1999                   4e trimestre 1999                  1999年第四季度

   yMMMM               October 1999                       octobre 1999                       1999年10月 

   MMMMd               October 13                         13 octobre                         10月13日 

   hhmm                11:58 PM                           11:58 PM                           下午11:58

   jjmm                11:58 PM                           23:58                              下午11:58

**************************************************************************************************************/
// Use DateTime.getPatternInstance to produce the same Date/Time format with predefined constant field value
final String[] dtfskeleton = {
        DateFormat.YEAR_QUARTER, // year + full name of quarter, i.e., 4th quarter 1999
        DateFormat.YEAR_MONTH,   // year + full name of month, i.e., October 1999
        DateFormat.MONTH_DAY     // full name of month + day of the month, i.e., October 25
        };
System.out.printf("%-20s%-35s%-35s%-35s\n\n", "Skeleton", "en_US", "fr_FR","zh_CN");
for (String skeleton:dtfskeleton) {
    System.out.printf("%-20s", skeleton);
    for (ULocale locale:locales) {
        // Use DateFormat.getPatternInstance to get the date/time format for the locale,
        // and apply the format to the given date
        String df=DateFormat.getPatternInstance(skeleton,locale).format(date);
        System.out.printf("%-35s",df);
    }
    System.out.println("\n");
}

/** output of the sample code:
 ************************************************************************************************************
 Skeleton            en_US                              fr_FR                              zh_CN

 yQQQQ               4th quarter 1999                   4e trimestre 1999                  1999年第四季度

 yMMMM               October 1999                       octobre 1999                       1999年10月

 MMMMd               October 13                         13 octobre                         10月13日 
 ************************************************************************************************************/

Parameters
skeleton String: The skeleton is a pattern containing only the variable fields. For example, "MMMdd" and "mmhh" are skeletons.
Returns
String Best pattern matching the input skeleton.

getDateTimeFormat

Added in API level 24
String getDateTimeFormat ()

Getter corresponding to setDateTimeFormat.

Returns
String pattern

getDecimal

Added in API level 24
String getDecimal ()

Getter corresponding to setDecimal.

Returns
String string corresponding to the decimal point

getEmptyInstance

Added in API level 24
DateTimePatternGenerator getEmptyInstance ()

Create empty generator, to be constructed with addPattern(...) etc.

Returns
DateTimePatternGenerator

getInstance

Added in API level 24
DateTimePatternGenerator getInstance ()

Construct a flexible generator according to data for the default FORMAT locale.

Returns
DateTimePatternGenerator

See also:

getInstance

Added in API level 24
DateTimePatternGenerator getInstance (Locale locale)

Construct a flexible generator according to data for a given locale.

Parameters
locale Locale: The Locale to pass.
Returns
DateTimePatternGenerator

getInstance

Added in API level 24
DateTimePatternGenerator getInstance (ULocale uLocale)

Construct a flexible generator according to data for a given locale.

Parameters
uLocale ULocale: The locale to pass.
Returns
DateTimePatternGenerator

getSkeleton

Added in API level 24
String getSkeleton (String pattern)

Utility to return a unique skeleton from a given pattern. For example, both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".

Parameters
pattern String: Input pattern, such as "dd/MMM"
Returns
String skeleton, such as "MMMdd"

getSkeletons

Added in API level 24
Map<StringString> getSkeletons (Map<StringString> result)

Return a list of all the skeletons (in canonical form) from this class, and the patterns that they map to.

Parameters
result Map: an output Map in which to place the mapping from skeleton to pattern. If you want to see the internal order being used, supply a LinkedHashMap. If the input value is null, then a LinkedHashMap is allocated.

Issue: an alternate API would be to just return a list of the skeletons, and then have a separate routine to get from skeleton to pattern.

Returns
Map<StringString> the input Map containing the values.

isFrozen

Added in API level 24
boolean isFrozen ()

Determines whether the object has been frozen or not.

Returns
boolean

replaceFieldTypes

Added in API level 24
String replaceFieldTypes (String pattern, 
                String skeleton)

Adjusts the field types (width and subtype) of a pattern to match what is in a skeleton. That is, if you supply a pattern like "d-M H:m", and a skeleton of "MMMMddhhmm", then the input pattern is adjusted to be "dd-MMMM hh:mm". This is used internally to get the best match for the input skeleton, but can also be used externally.

Example code:

Date date= new GregorianCalendar(1999,9,13,23,58,59).getTime();
TimeZone zone = TimeZone.getTimeZone("Europe/Paris");
ULocale locale = ULocale.FRANCE;
DateTimePatternGenerator gen = DateTimePatternGenerator.getInstance(locale);
SimpleDateFormat format = new SimpleDateFormat("EEEE d MMMM y HH:mm:ss zzzz",locale);
format.setTimeZone(zone);
String pattern = format.toPattern();
System.out.println("Pattern before replacement:");
System.out.println(pattern);
System.out.println("Date/Time format in fr_FR:");
System.out.println(format.format(date));
// Replace zone "zzzz" in the pattern with "vvvv"
String newPattern = gen.replaceFieldTypes(pattern, "vvvv");
// Apply the new pattern
format.applyPattern(newPattern);
System.out.println("Pattern after replacement:");
System.out.println(newPattern);
System.out.println("Date/Time format in fr_FR:");
System.out.println(format.format(date));

/** output of the sample code:
***************************************************************************************************
 Pattern before replacement:
 EEEE d MMMM y HH:mm:ss zzzz
 Date/Time format in fr_FR:
 jeudi 14 octobre 1999 05:58:59 heure avancée d’Europe centrale
 Pattern after replacement:
 EEEE d MMMM y HH:mm:ss vvvv
 Date/Time format in fr_FR:
 jeudi 14 octobre 1999 05:58:59 heure de l’Europe centrale

**************************************************************************************************/

Parameters
pattern String: input pattern
skeleton String: For the pattern to match to.
Returns
String pattern adjusted to match the skeleton fields widths and subtypes.

replaceFieldTypes

Added in API level 24
String replaceFieldTypes (String pattern, 
                String skeleton, 
                int options)

Adjusts the field types (width and subtype) of a pattern to match what is in a skeleton. That is, if you supply a pattern like "d-M H:m", and a skeleton of "MMMMddhhmm", then the input pattern is adjusted to be "dd-MMMM hh:mm". This is used internally to get the best match for the input skeleton, but can also be used externally.

Parameters
pattern String: input pattern
skeleton String: For the pattern to match to.
options int: MATCH_xxx options for forcing the length of specified fields in the returned pattern to match those in the skeleton (when this would not happen otherwise). For default behavior, use MATCH_NO_OPTIONS.
Returns
String pattern adjusted to match the skeleton fields widths and subtypes.

setAppendItemFormat

Added in API level 24
void setAppendItemFormat (int field, 
                String value)

An AppendItem format is a pattern used to append a field if there is no good match. For example, suppose that the input skeleton is "GyyyyMMMd", and there is no matching pattern internally, but there is a pattern matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the G. The way these two are conjoined is by using the AppendItemFormat for G (era). So if that value is, say "{0}, {1}" then the final resulting pattern is "d-MM-yyyy, G".

There are actually three available variables: {0} is the pattern so far, {1} is the element we are adding, and {2} is the name of the element.

This reflects the way that the CLDR data is organized.

Parameters
field int: such as ERA
value String: pattern, such as "{0}, {1}"

setAppendItemName

Added in API level 24
void setAppendItemName (int field, 
                String value)

Sets the names of fields, eg "era" in English for ERA. These are only used if the corresponding AppendItemFormat is used, and if it contains a {2} variable.

This reflects the way that the CLDR data is organized.

Parameters
field int: Index of the append item names.
value String: The value to set the item to.

setDateTimeFormat

Added in API level 24
void setDateTimeFormat (String dateTimeFormat)

The date time format is a message format pattern used to compose date and time patterns. The default value is "{1} {0}", where {1} will be replaced by the date pattern and {0} will be replaced by the time pattern.

This is used when the input skeleton contains both date and time fields, but there is not a close match among the added patterns. For example, suppose that this object was created by adding "dd-MMM" and "hh:mm", and its datetimeFormat is the default "{1} {0}". Then if the input skeleton is "MMMdhmm", there is not an exact match, so the input skeleton is broken up into two components "MMMd" and "hmm". There are close matches for those two skeletons, so the result is put together with this pattern, resulting in "d-MMM h:mm".

Parameters
dateTimeFormat String: message format pattern, where {1} will be replaced by the date pattern and {0} will be replaced by the time pattern.

setDecimal

Added in API level 24
void setDecimal (String decimal)

The decimal value is used in formatting fractions of seconds. If the skeleton contains fractional seconds, then this is used with the fractional seconds. For example, suppose that the input pattern is "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and the decimal string is ",". Then the resulting pattern is modified to be "H:mm:ss,SSSS"

Parameters
decimal String: The decimal to set to.

Hooray!