Home Reference Source
public class | source

DateTimeFormatter

Static properties of Class DateTimeFormatter

DateTimeFormatter.ISO_LOCAL_DATE

DateTimeFormatter.ISO_LOCAL_TIME

DateTimeFormatter.ISO_LOCAL_DATE_TIME

Static Method Summary

Static Public Methods
public static

ofPattern(pattern: String): DateTimeFormatter

Creates a formatter using the specified pattern.

public static

A query that provides access to the excess days that were parsed.

public static

A query that provides access to whether a leap-second was parsed.

Method Summary

Public Methods
public

chronology(): *

public
public

format(temporal: TemporalAccessor): String

Formats a date-time object using this formatter.

public

locale(): *

public

parse(text: string, type: TemporalQuery): TemporalAccessor

function overloading for DateTimeFormatter.parse

public

parse1(text: String): TemporalAccessor

Fully parses the text producing a temporal object.

public

parse2(text: *, type: *): *

Fully parses the text producing a temporal object.

public

parseUnresolved(text: *, position: *): *

Parses the text using this formatter, without resolving the result, intended for advanced use cases.

public

toString(): string

public

withChronology(chrono: *): *

Returns a copy of this formatter with a new override chronology.

public

not yet supported

public

Returns a copy of this formatter with a new resolver style.

Static Public Methods

public static ofPattern(pattern: String): DateTimeFormatter source

Creates a formatter using the specified pattern.

This method will create a formatter based on a simple pattern of letters and symbols.

The returned formatter will use the default locale, but this can be changed using DateTimeFormatter.withLocale.

All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:

 |Symbol  |Meaning                     |Presentation      |Examples
 |--------|----------------------------|------------------|----------------------------------------------------
 | G      | era                        | number/text      | 1; 01; AD; Anno Domini
 | u      | year                       | year             | 2004; 04
 | y      | year-of-era                | year             | 2004; 04
 | D      | day-of-year                | number           | 189
 | M      | month-of-year              | number/text      | 7; 07; Jul; July; J
 | d      | day-of-month               | number           | 10
 |        |                            |                  |
 | Q      | quarter-of-year            | number/text      | 3; 03; Q3
 | Y      | week-based-year            | year             | 1996; 96
 | w      | week-of-year               | number           | 27
 | W      | week-of-month              | number           | 27
 | e      | localized day-of-week      | number           | 2; Tue; Tuesday; T
 | E      | day-of-week                | number/text      | 2; Tue; Tuesday; T
 | F      | week-of-month              | number           | 3
 |        |                            |                  |
 | a      | am-pm-of-day               | text             | PM
 | h      | clock-hour-of-am-pm (1-12) | number           | 12
 | K      | hour-of-am-pm (0-11)       | number           | 0
 | k      | clock-hour-of-am-pm (1-24) | number           | 0
 |        |                            |                  |
 | H      | hour-of-day (0-23)         | number           | 0
 | m      | minute-of-hour             | number           | 30
 | s      | second-of-minute           | number           | 55
 | S      | fraction-of-second         | fraction         | 978
 | A      | milli-of-day               | number           | 1234
 | n      | nano-of-second             | number           | 987654321
 | N      | nano-of-day                | number           | 1234000000
 |        |                            |                  |
 | V      | time-zone ID               | zone-id          | America/Los_Angeles; Z; -08:30
 | z      | time-zone name             | zone-name        | Pacific Standard Time; PST
 | X      | zone-offset 'Z' for zero   | offset-X         | Z; -08; -0830; -08:30; -083015; -08:30:15;
 | x      | zone-offset                | offset-x         | +0000; -08; -0830; -08:30; -083015; -08:30:15;
 | Z      | zone-offset                | offset-Z         | +0000; -0800; -08:00;
 |        |                            |                  |
 | p      | pad next                   | pad modifier     | 1
 |        |                            |                  |
 | '      | escape for text            | delimiter        |
 | ''     | single quote               | literal          | '
 | [      | optional section start     |                  |
 | ]      | optional section end       |                  |
 | {}     | reserved for future use    |                  |

The count of pattern letters determine the format.

Text: The text style is determined based on the number of pattern letters used. Less than 4 pattern letters will use the short form TextStyle.SHORT. Exactly 4 pattern letters will use the full form TextStyle.FULL. Exactly 5 pattern letters will use the narrow form TextStyle.NARROW.

NOTE: since text styles require locale support, they are currently not supported in js-joda!

Number: If the count of letters is one, then the value is printed using the minimum number of digits and without padding as per DateTimeFormatterBuilder.appendValue. Otherwise, the count of digits is used as the width of the output field as per DateTimeFormatterBuilder.appendValue.

Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.

Fraction: Outputs the nano-of-second field as a fraction-of-second. The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9. If it is less than 9, then the nano-of-second value is truncated, with only the most significant digits being output. When parsing in strict mode, the number of parsed digits must match the count of pattern letters. When parsing in lenient mode, the number of parsed digits must be at least the count of pattern letters, up to 9 digits.

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a DateTimeFormatterBuilder.appendValueReduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive. If the count of letters is less than four (but not two), then the sign is only output for negative years as per SignStyle.NORMAL. Otherwise, the sign is output if the pad width is exceeded, as per SignStyle.EXCEEDS_PAD

ZoneId: This outputs the time-zone ID, such as 'Europe/Paris'. If the count of letters is two, then the time-zone ID is output. Any other count of letters throws IllegalArgumentException.

Zone names: This outputs the display name of the time-zone ID. If the count of letters is one, two or three, then the short name is output. If the count of letters is four, then the full name is output. Five or more letters throws IllegalArgumentException.

NOTE: since zone ids and name require the iana tzdb, they are currently not supported in js-joda!

Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour', such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. Four or more letters throws IllegalArgumentException. The output will be '+0000' when the offset is zero.

Optional section: The optional section markers work exactly like calling DateTimeFormatterBuilder.optionalStart and DateTimeFormatterBuilder.optionalEnd.

Pad modifier: Modifies the pattern that immediately follows to be padded with spaces. The pad width is determined by the number of pattern letters. This is the same as calling DateTimeFormatterBuilder.padNext.

For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.

Any unrecognized letter is an error. Any non-letter character, other than '[', ']', '{', '}' and the single quote will be output directly. Despite this, it is recommended to use single quotes around all characters that you want to output directly to ensure that future changes do not break your application.

Params:

NameTypeAttributeDescription
pattern String

the pattern to use, not null

Return:

DateTimeFormatter

the formatter based on the pattern, not null

Throw:

*

IllegalArgumentException if the pattern is invalid

Example:

var s = LocalDate.parse('2016-04-01').format(DateTimeFormatter.ofPattern('d MM yyyy'));
console.log(s); // '1 04 2016'

See:

public static parsedExcessDays(): TemporalQuery source

A query that provides access to the excess days that were parsed.

This returns a singleton TemporalQuery that provides access to additional information from the parse. The query always returns a non-null period, with a zero period returned instead of null.

There are two situations where this query may return a non-zero period.

  • If the ResolverStyle is LENIENT and a time is parsed without a date, then the complete result of the parse consists of a LocalTime and an excess Period in days.
  • If the ResolverStyle is SMART and a time is parsed without a date where the time is 24:00:00, then the complete result of the parse consists of a LocalTime of 00:00:00 and an excess Period of one day.

In both cases, if a complete ChronoLocalDateTime or Instant is parsed, then the excess days are added to the date part. As a result, this query will return a zero period.

The SMART behaviour handles the common "end of day" 24:00 value. Processing in LENIENT mode also produces the same result:

 Text to parse        Parsed object                         Excess days
 "2012-12-03T00:00"   LocalDateTime.of(2012, 12, 3, 0, 0)   ZERO
 "2012-12-03T24:00"   LocalDateTime.of(2012, 12, 4, 0, 0)   ZERO
 "00:00"              LocalTime.of(0, 0)                    ZERO
 "24:00"              LocalTime.of(0, 0)                    Period.ofDays(1)
The query can be used as follows:
 TemporalAccessor parsed = formatter.parse(str);
 LocalTime time = parsed.query(LocalTime.FROM);
 Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays());

Return:

TemporalQuery

a query that provides access to the excess days that were parsed

public static parsedLeapSecond(): * source

A query that provides access to whether a leap-second was parsed.

This returns a singleton TemporalQuery that provides access to additional information from the parse. The query always returns a non-null boolean, true if parsing saw a leap-second, false if not.

Instant parsing handles the special "leap second" time of '23:59:60'. Leap seconds occur at '23:59:60' in the UTC time-zone, but at other local times in different time-zones. To avoid this potential ambiguity, the handling of leap-seconds is limited to DateTimeFormatterBuilder#appendInstant, as that method always parses the instant with the UTC zone offset.

If the time '23:59:60' is received, then a simple conversion is applied, replacing the second-of-minute of 60 with 59. This query can be used on the parse result to determine if the leap-second adjustment was made. The query will return one second of excess if it did adjust to remove the leap-second, and zero if not. Note that applying a leap-second smoothing mechanism, such as UTC-SLS, is the responsibility of the application, as follows:

 TemporalAccessor parsed = formatter.parse(str);
 Instant instant = parsed.query(Instant::from);
 if (parsed.query(DateTimeFormatter.parsedLeapSecond())) {
   // validate leap-second is correct and apply correct smoothing
 }

Return:

*

a query that provides access to whether a leap-second was parsed

Public Methods

public chronology(): * source

Return:

*

public decimalStyle(): * source

Return:

*

public format(temporal: TemporalAccessor): String source

Formats a date-time object using this formatter.

This formats the date-time to a String using the rules of the formatter.

Params:

NameTypeAttributeDescription
temporal TemporalAccessor

the temporal object to print, not null

Return:

String

the printed string, not null

Throw:

*

DateTimeException if an error occurs during formatting

public locale(): * source

Return:

*

public parse(text: string, type: TemporalQuery): TemporalAccessor source

function overloading for DateTimeFormatter.parse

if called with one arg DateTimeFormatter.parse1 is called otherwise DateTimeFormatter.parse2

Params:

NameTypeAttributeDescription
text string
type TemporalQuery

public parse1(text: String): TemporalAccessor source

Fully parses the text producing a temporal object.

This parses the entire text producing a temporal object. It is typically more useful to use parse. The result of this method is TemporalAccessor which has been resolved, applying basic validation checks to help ensure a valid date-time.

If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.

Params:

NameTypeAttributeDescription
text String

the text to parse, not null

Return:

TemporalAccessor

the parsed temporal object, not null

Throw:

*

DateTimeParseException if unable to parse the requested result

public parse2(text: *, type: *): * source

Fully parses the text producing a temporal object.

This parses the entire text producing a temporal object. It is typically more useful to use parse. The result of this method is TemporalAccessor which has been resolved, applying basic validation checks to help ensure a valid date-time.

If the parse completes without reading the entire length of the text, or a problem occurs during parsing or merging, then an exception is thrown.

Params:

NameTypeAttributeDescription
text *

the text to parse, not null

type *

the type to extract, not null

Return:

*

the parsed temporal object, not null

Throw:

*

DateTimeParseException if unable to parse the requested result

public parseUnresolved(text: *, position: *): * source

Parses the text using this formatter, without resolving the result, intended for advanced use cases.

Parsing is implemented as a two-phase operation. First, the text is parsed using the layout defined by the formatter, producing a Map of field to value, a ZoneId and a Chronology. Second, the parsed data is resolved, by validating, combining and simplifying the various fields into more useful ones. This method performs the parsing stage but not the resolving stage.

The result of this method is TemporalAccessor which represents the data as seen in the input. Values are not validated, thus parsing a date string of '2012-00-65' would result in a temporal with three fields - year of '2012', month of '0' and day-of-month of '65'.

The text will be parsed from the specified start ParsePosition. The entire length of the text does not have to be parsed, the ParsePosition will be updated with the index at the end of parsing.

Errors are returned using the error index field of the ParsePosition instead of DateTimeParseException. The returned error index will be set to an index indicative of the error. Callers must check for errors before using the context.

If the formatter parses the same field more than once with different values, the result will be an error.

This method is intended for advanced use cases that need access to the internal state during parsing. Typical application code should use parse or the parse method on the target type.

Params:

NameTypeAttributeDescription
text *

the text to parse, not null

position *

the position to parse from, updated with length parsed and the index of any error, not null

Return:

*

the parsed text, null if the parse results in an error

Throw:

*

DateTimeException if some problem occurs during parsing

*

IndexOutOfBoundsException if the position is invalid

public toString(): string source

Return:

string

public withChronology(chrono: *): * source

Returns a copy of this formatter with a new override chronology.

This returns a formatter with similar state to this formatter but with the override chronology set. By default, a formatter has no override chronology, returning null.

If an override is added, then any date that is printed or parsed will be affected.

When printing, if the Temporal object contains a date then it will be converted to a date in the override chronology. Any time or zone will be retained unless overridden. The converted result will behave in a manner equivalent to an implementation of ChronoLocalDate,ChronoLocalDateTime or ChronoZonedDateTime.

When parsing, the override chronology will be used to interpret the ChronoField into a date unless the formatter directly parses a valid chronology.

This instance is immutable and unaffected by this method call.

Params:

NameTypeAttributeDescription
chrono *

the new chronology, not null

Return:

*

a formatter based on this formatter with the requested override chronology, not null

public withLocale(): DateTimeFormatter source

not yet supported

public withResolverStyle(resolverStyle: ResolverStyle): DateTimeFormatter source

Returns a copy of this formatter with a new resolver style.

This returns a formatter with similar state to this formatter but with the resolver style set. By default, a formatter has the {@link ResolverStyle#SMART SMART} resolver style.

Changing the resolver style only has an effect during parsing. Parsing a text string occurs in two phases. Phase 1 is a basic text parse according to the fields added to the builder. Phase 2 resolves the parsed field-value pairs into date and/or time objects. The resolver style is used to control how phase 2, resolving, happens. See ResolverStyle for more information on the options available.

This instance is immutable and unaffected by this method call.

Params:

NameTypeAttributeDescription
resolverStyle ResolverStyle

the new resolver style, not null

Return:

DateTimeFormatter

a formatter based on this formatter with the requested resolver style, not null