Java DateTimeFormatter
December 21, 2018
DateTimeFormatter
is a formatter that is used to print and parse date-time objects. It has been introduced in Java 8. DateTimeFormatter
is immutable and thread-safe. DateTimeFormatter
formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter
can be created with desired Locale, Chronology, ZoneId, and DecimalStyle. DateTimeFormatter
is instantiated with a date-time format string by using its ofPattern
method.
Find sample example to instantiate
DateTimeFormatter
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
String dateTime = formatter.format(LocalDateTime.now()); System.out.println(dateTime); //2018-Dec-21 11:14:12
LocalDateTime ldt = LocalDateTime.parse("2018-Dec-20 08:25:30", formatter); System.out.println(ldt); //2018-12-20T08:25:30
DateTimeFormatter
with examples and format LocalDate
, LocalDateTime
and LocalTime
instnaces.
Contents
- Instantiate DateTimeFormatter
- DateTimeFormatter format() and formatTo()
- Formatting LocalDate
- Formatting LocalDateTime
- Formatting LocalTime
- DateTimeFormatter "parse" Methods
- DateTimeFormatter "with" Methods
- DateTimeFormatter "get" Methods
- Convert DateTimeFormatter to Format
- Predefined Formatters
- Pattern Letters and Symbols
- References
Instantiate DateTimeFormatter
DateTimeFormatter
has following static methods to instantiate DateTimeFormatter
.
1. ofPattern(String pattern): Creates formatter using given pattern.
2. ofPattern(String pattern, Locale locale): Creates formatter using given pattern and locale.
3. ofLocalizedDate(FormatStyle dateStyle): Creates formatter with a locale specific date format.
FormatStyle
is an enum
whose values can be FULL, LONG, MEDIUM, SHORT.
4. ofLocalizedDateTime(FormatStyle dateTimeStyle): Creates formatter with a locale specific date-time format.
5. ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle): Creates formatter with a locale specific date-time format. We need to pass
FormatStyle
for date and time separately. For example date can be LONG and time can be SHORT.
6. ofLocalizedTime(FormatStyle timeStyle): Creates formatter with a locale specific time format.
Find the sample examples.
package com.concretepage; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Locale; public class DateTimeFormatterDemo { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MMM dd, yyyy"); String formattedDate1 = formatter1.format(localDate); System.out.println(formattedDate1); //Dec 17, 2018 DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.CANADA); String formattedDate2 = formatter2.format(localDate); System.out.println(formattedDate2); //Dec. 17, 2018 DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL); String formattedDate3 = formatter3.format(localDate); System.out.println(formattedDate3); //Monday, December 17, 2018 LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter formatter4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); String formattedDate4 = formatter4.format(localDateTime); System.out.println(formattedDate4); //Dec 17, 2018, 9:14:39 PM DateTimeFormatter formatter5 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT); String formattedDate5 = formatter5.format(localDateTime); System.out.println(formattedDate5); //December 17, 2018, 9:14 PM LocalTime localTime = LocalTime.now(); DateTimeFormatter formatter6 = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM); String formattedDate6 = formatter6.format(localTime); System.out.println(formattedDate6); //9:14:39 PM } }
Dec 17, 2018 Dec. 17, 2018 Monday, December 17, 2018 Dec 17, 2018, 9:14:39 PM December 17, 2018, 9:14 PM 9:14:39 PM
FormatStyle:
It is an
enum
of the style of localized date, time or date-time formatter. It has following constants.
1. FULL such as 'Tuesday, April 11, 2015 AD' or '5:30:45pm PST'.
2. LONG such as 'January 10, 2018'.
3. MEDIUM such as 'Jan 10, 2018'
4. SHORT such as '11.15.50' or '6:30pm'.
DateTimeFormatter format() and formatTo()
To format a date, time or date-time,DateTimeFormatter
provides following methods.
1. format(TemporalAccessor temporal): Formats the given date-time object using this formatter and returns as string.
2. formatTo(TemporalAccessor temporal, Appendable appendable): Formats the given date-time object using this formatter and appends result into given
Appendable
object. Appendable
object can be instance of StringBuffer
, StringBuilder
etc.
Find the sample example.
package com.concretepage; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss"); LocalDateTime ldt = LocalDateTime.now(); System.out.println(dtf.format(ldt)); //2018-Dec-20 03:50:45 StringBuffer sb = new StringBuffer("Date "); dtf.formatTo(ldt, sb); System.out.println(sb); //Date 2018-Dec-20 03:50:45 } }
2018-Dec-20 03:50:45 Date 2018-Dec-20 03:50:45
Formatting LocalDate
LocalDate
is a date without a time-zone in the ISO-8601 calendar system. Find the examples to format LocalDate
using DateTimeFormatter
.
package com.concretepage; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd"); LocalDate ld = LocalDate.now(); System.out.println(dtf.format(ld)); //2018-Dec-20 dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd(E)"); ld = LocalDate.now(); System.out.println(dtf.format(ld)); //2018-Dec-20(Thu) dtf = DateTimeFormatter.ofPattern("MMM dd, YYYY"); ld = LocalDate.now(); System.out.println(dtf.format(ld)); //Dec 20, 2018 } }
2018-Dec-20 2018-Dec-20(Thu) Dec 20, 2018
DateTimeFormatter
is also used to parse a local date. Find the sample code.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, yyyy"); LocalDate ld = LocalDate.parse("Dec 20, 2018", dtf); System.out.println(ld);
2018-12-20
Formatting LocalDateTime
LocalDateTime
is a date-time without a time-zone in the ISO-8601 calendar system. Find the sample examples to format LocalDateTime
using DateTimeFormatter
.
package com.concretepage; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss"); LocalDateTime ldt = LocalDateTime.now(); System.out.println(dtf.format(ldt)); //2018-Dec-20 07:40:03 dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd(E) hh:mm:ss a"); ldt = LocalDateTime.now(); System.out.println(dtf.format(ldt)); //2018-Dec-20(Thu) 07:40:03 PM dtf = DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss"); ldt = LocalDateTime.now(); System.out.println(dtf.format(ldt)); //18-12-20 19:40:03 } }
2018-Dec-20 07:40:03 2018-Dec-20(Thu) 07:40:03 PM 18-12-20 19:40:03
DateTimeFormatter
is also used to parse a local date-time. Find the sample code.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss"); LocalDateTime ldt = LocalDateTime.parse("2018-Dec-20 08:25:30", dtf); System.out.println(ldt);
2018-12-20T08:25:30
Formatting LocalTime
LocalTime
is a time without a time-zone in the ISO-8601 calendar system. Find the examples to format LocalTime
using DateTimeFormatter
.
package com.concretepage; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm:ss"); LocalTime lt = LocalTime.now(); System.out.println(dtf.format(lt)); //08:03:32 dtf = DateTimeFormatter.ofPattern("hh:mm:ss a"); lt = LocalTime.now(); System.out.println(dtf.format(lt)); //08:03:32 PM dtf = DateTimeFormatter.ofPattern("HH:mm"); lt = LocalTime.now(); System.out.println(dtf.format(lt)); //20:03 } }
08:03:32 08:03:32 PM 20:03
DateTimeFormatter
is also used to parse a local time. Find the sample code.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss"); LocalTime lt = LocalTime.parse("08:25:30", dtf); System.out.println(lt);
08:25:30
DateTimeFormatter "parse" Methods
DateTimeFormatter
provides following methods to parse a text.
1.
TemporalAccessor parse(CharSequence text)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss"); TemporalAccessor ta = formatter.parse("18-Dec-2017 02:46:41"); System.out.println(ta.get(ChronoField.YEAR)); System.out.println(ta.get(ChronoField.HOUR_OF_AMPM));
2017 2
TemporalAccessor parse(CharSequence text, ParsePosition position)
ParsePosition
to escape some characters in given text. We initiate a ParsePosition
with given initial index from where parse
method will start parsing given text.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss"); TemporalAccessor ta = formatter.parse("Date 18-Dec-2017 02:46:41", new ParsePosition(5)); System.out.println(ta.get(ChronoField.YEAR)); System.out.println(ta.get(ChronoField.HOUR_OF_AMPM));
2017 2
<T> T parse(CharSequence text, TemporalQuery<T> query)
TemporalQuery
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss"); LocalDate localDate = formatter.parse("18-Dec-2017 02:46:41", TemporalQueries.localDate()); System.out.println(localDate);
2017-12-18
TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss"); TemporalAccessor ta = formatter.parseBest("18-Dec-2017 02:46:41", TemporalQueries.localDate(), TemporalQueries.localTime()); System.out.println(ta);
2017-12-18
TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position)
ParsePosition
but does not resolve it. It means even if month day is 38, it will not throw error.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss"); TemporalAccessor ta = formatter.parseUnresolved("Date 38-Dec-2017 02:46:41", new ParsePosition(5)); System.out.println(ta);
{DayOfMonth=38, ClockHourOfAmPm=2, MinuteOfHour=46, YearOfEra=2017, SecondOfMinute=41, MonthOfYear=12},null
static TemporalQuery<Period> parsedExcessDays()
Period
that has been parsed.
package com.concretepage; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("HH:mm"); TemporalAccessor parsed1 = formatter1.parse("24:00"); LocalTime lt1 = parsed1.query(LocalTime::from); Period excessDays1 = parsed1.query(DateTimeFormatter.parsedExcessDays()); System.out.println(lt1 + " , " + excessDays1); //00:00 , P1D DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); TemporalAccessor parsed2 = formatter2.parse("2018-12-03 24:00"); LocalDateTime lt2 = parsed2.query(LocalDateTime::from); Period excessDays2 = parsed2.query(DateTimeFormatter.parsedExcessDays()); System.out.println(lt2 + " , " + excessDays2); //2018-12-04T00:00 , P0D } }
00:00 , P1D 2018-12-04T00:00 , P0D
7.
static TemporalQuery<Boolean> parsedLeapSecond()
package com.concretepage; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; TemporalAccessor parsed = formatter.parse("2017-12-31T23:59:60Z"); Instant instant = parsed.query(Instant::from); System.out.println(instant); System.out.println("leap second parsed=" + parsed.query(DateTimeFormatter.parsedLeapSecond())); } }
2017-12-31T23:59:59Z leap second parsed=true
DateTimeFormatter.ISO_INSTANT
formats an instant in UTC.
DateTimeFormatter "with" Methods
Following methods returnDateTimeFormatter
instance.
1. withChronology(Chronology chrono): Returns a copy of this formatter with given chronology.
2. withDecimalStyle(DecimalStyle decimalStyle): Returns a copy of this formatter with given decimal style.
3. withLocale(Locale locale): Returns a copy of this formatter with given locale.
4. withResolverFields(TemporalField... resolverFields): Returns a copy of this formatter with given temporal fields.
5. withResolverFields(Set<TemporalField> resolverFields): Returns a copy of this formatter with given temporal fields as
Set
.
6. withResolverStyle(ResolverStyle resolverStyle): Returns a copy of this formatter with given resolver style.
7. withZone(ZoneId zone): Returns a copy of this formatter with given zone id.
We can use the above methods while instantiating
DateTimeFormatter
using DateTimeFormatterBuilder
. Find the sample code.
package com.concretepage; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DecimalStyle; import java.time.format.ResolverStyle; import java.time.format.TextStyle; import java.time.temporal.ChronoField; import java.util.Locale; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); DateTimeFormatter formatter = builder.appendLiteral("Day is:") .appendValue(ChronoField.DAY_OF_MONTH) .appendLiteral(", month is:") .appendValue(ChronoField.MONTH_OF_YEAR) .appendLiteral(", and year:") .appendPattern("u") .appendLiteral(" with the time:") .appendValue(ChronoField.HOUR_OF_DAY) .appendLiteral(":") .appendText(ChronoField.MINUTE_OF_HOUR, TextStyle.NARROW_STANDALONE) .toFormatter() .withDecimalStyle(DecimalStyle.STANDARD) .withChronology(IsoChronology.INSTANCE) .withLocale(Locale.CANADA) .withResolverStyle(ResolverStyle.LENIENT) .withZone(ZoneId.systemDefault()); LocalDateTime dateTime = LocalDateTime.now(); String str = dateTime.format(formatter); System.out.println(str); } }
Day is:20, month is:12, and year:2018 with the time:11:36
DateTimeFormatter "get" Methods
We can fetchDateTimeFormatter
object information using following methods.
getChronology(): Gets chronology.
getDecimalStyle(): Gets decimal style.
getLocale(): Gets locale.
getResolverFields(): Gets resolver fields.
getResolverStyle(): Gets resolver style.
getZone(): Gets zone.
Find the sample example.
package com.concretepage; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME; System.out.println("Chronology: " + dtf.getChronology()); System.out.println("DecimalStyle: " + dtf.getDecimalStyle()); System.out.println("Locale: "+ dtf.getLocale()); System.out.println("ResolverFields: "+ dtf.getResolverFields()); System.out.println("ResolverStyle: "+ dtf.getResolverStyle()); System.out.println("Zone: "+ dtf.getZone()); } }
Chronology: ISO DecimalStyle: DecimalStyle[0+-.] Locale: en_US ResolverFields: null ResolverStyle: STRICT Zone: null
Convert DateTimeFormatter to Format
DateTimeFormatter
provide following methods to convert DateTimeFormatter
to java.text.Format
.
1. toFormat(): Returns
java.text.Format
instance.
2. toFormat(TemporalQuery<?> parseQuery): Returns
java.text.Format
instance that will parse using given query.
Find the sample example.
package com.concretepage; import java.text.Format; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("MMM dd, yyyy"); Format format1 = dtf1.toFormat(); String ld = format1.format(LocalDate.parse("2017-12-20")); System.out.println(ld); //Dec 20, 2017 DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("HH:mm:ss"); Format format2 = dtf2.toFormat(); String time = format2.format(LocalDateTime.now()); System.out.println(time); //12:34:23 } }
Dec 20, 2017 12:34:23
Predefined Formatters
DateTimeFormatter
has following predefined formatters. Formatter | Example |
---|---|
BASIC_ISO_DATE | '20181203' |
ISO_LOCAL_DATE | '2018-12-03' |
ISO_OFFSET_DATE | '2018-12-03+01:00' |
ISO_DATE | '2018-12-03+01:00'; '2018-12-03' |
ISO_LOCAL_TIME | '11:15:30' |
ISO_OFFSET_TIME | '11:15:30+01:00' |
ISO_TIME | '11:15:30+01:00'; '11:15:30' |
ISO_LOCAL_DATE_TIME | '2018-12-03T11:15:30' |
ISO_OFFSET_DATE_TIME | '2018-12-03T11:15:30+01:00' |
ISO_ZONED_DATE_TIME | '2018-12-03T11:15:30+01:00[Europe/Paris]' |
ISO_DATE_TIME | '2018-12-03T11:15:30+01:00[Europe/Paris]' |
ISO_ORDINAL_DATE | '2018-337' |
ISO_WEEK_DATE | '2018-W48-6' |
ISO_INSTANT | '2018-12-03T11:15:30Z' |
RFC_1123_DATE_TIME | 'Tue, 3 Jun 2018 11:05:30 GMT' |
ISO_WEEK_DATE
to print and parse local date. Find the code.
package com.concretepage; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateTimeFormatterDemo { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ISO_WEEK_DATE; String dateTime = formatter.format(LocalDate.now()); System.out.println(dateTime); //2018-W51-5 LocalDate ld = LocalDate.parse("2018-W40-4", formatter); System.out.println(ld); //2018-10-04 } }
2018-W51-5 2018-10-04
Pattern Letters and Symbols
Find the pattern letters and symbols to format date-time.Symbol | Description | Example |
---|---|---|
G | era | AD; Anno Domini; A |
u | year | 2018; 18 |
y | year-of-era | 2018; 18 |
D | day-of-year | 180 |
M/L | month-of-year | 7; 07; Jul; July; J |
d | day-of-month | 11 |
g | modified-julian-day | 2451334 |
Q/q | quarter-of-year | 3; 03; Q3; 3rd quarter |
Y | week-based-year | 1999; 99 |
w | week-of-week-based-year | 25 |
W | week-of-month | 3 |
E | day-of-week | Tue; Tuesday; T |
e/c | localized day-of-week | 2; 02; Tue; Tuesday; T |
F | day-of-week-in-month | 2 |
a | am-pm-of-day | AM |
h | clock-hour-of-am-pm (1-12) | 12 |
K | hour-of-am-pm (0-11 | 0 |
k | clock-hour-of-day (1-24) | 24 |
H | hour-of-day (0-23) | 0 |
m | minute-of-hour | 35 |
s | second-of-minute | 50 |
S | fraction-of-second | 970 |
A | milli-of-day | 1234 |
n | nano-of-second | 987654321 |
N | nano-of-day | 1234000000 |
V | time-zone ID | America/Los_Angeles; Z; -08:30 |
v | generic time-zone name | Pacific Time; PT |
z | time-zone name | Pacific Standard Time; PST |
O | localized zone-offset | GMT+8; GMT+08:00; UTC-08:00 |
X | zone-offset 'Z' for zero | Z; -08; -0830; -08:30; -083015; -08:30:15 |
x | zone-offset | +0000; -08; -0830; -08:30; -083015; -08:30:15 |
Z | zone-offset | +0000; -0800; -08:00 |
p | pad next | 1 |
' | escape for text | |
'' | single quote | ' |
[ | optional section start | |
] | optional section end |
References
Class DateTimeFormatterJava LocalDate