DateTimeFormatter class formats and parse a datetime object.
Parsing is the reverse of formatting which creates a datetime object from a textual representation of a datetime.
For example, create a LocalDate object from the text "05/24/2018" to represent May 24, 2018.
Formatting and parsing are always performed by an object of the DateTimeFormatter class.
Use one of the following two methods of the DateTimeFormatter class to format a date, time, or datetime:
String format(TemporalAccessor temporal)
void formatTo(TemporalAccessor temporal, Appendable appendable)
format() method takes a date, time, or datetime object and returns a String based on the rules of the formatter.
formatTo() method writes the textual representation of the object to an Appendable, for example, a file, a StringBuilder, etc.
You can perform formatting in several ways:
Predefined formatters are defined as constants in the DateTimeFormatter class which are listed in the following table.
Formatter | Description | Example |
---|---|---|
BASIC_ISO_DATE | format and parse a date without using a separator between two date components. | 20180109, 20180109-0600 |
ISO_DATE, ISO_TIME, ISO_DATE_TIME | Date, time, and datetime formatters to format and parse dates, times, and datetimes using the ISO separators. | 2018-01-09, 2018-01-09-06:00, 15:38:32.927, 15:38:32.943-06:00, 2018-01-09T15:20:07.747-06:00, 2018-01-09T15:20:07.825-06:00[America/Chicago] |
ISO_INSTANT | format and parse an instant (or a datetime object representing an instant such as a ZonedDateTime) in UTC format. | 2018-01-09T21:23:56.870Z |
ISO_LOCAL_DATE, ISO_LOCAL_TIME, ISO_LOCAL_DATE_TIME | Date, time, and datetime formatters to format or parse dates, times, and datetimes without an offset. | 2018-01-09, 15:30:14.352, 2018-01-09T15:29:11.384 |
ISO_OFFSET_DATE, ISO_OFFSET_TIME, ISO_OFFSET_DATE_TIME | Date, time, and datetime formatters to format and parse dates, times, and datetimes with an offset using ISO format. | 2018-01-09-06:00, 15:34:29.851-06:00, 2018-01-09T15:33:07.07-06:0 |
ISO_ZONED_DATE_TIME | A datetime formatter to format and parse a datetime with a zone id, if available. | 2018-01-09T15:45:49.112-06:00, 2018-01-09T15:45:49.128-06:00[America/Chicago] |
ISO_ORDINAL_DATE | A date formatter to format and parse a date with year and day-of-year. | 2018-009 |
ISO_WEEK_DATE | A date formatter to format and parse week- based dates. The format is year-Wweek_ of_year-day_of_week. For example, '2018-W02-4' means the fourth day of the second week in 2018. | 2018-W02-4, 2018-W02-4-06:00 |
RFC_1123_DATE_TIME | A datetime formatter to format and parse datetimes for e-mails using the RFC1123 specification. | Thu, 9 Jan 2018 15:50:44 -060 |