Java DateTimeFormatter

By Arvind Rai, 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"); 
Find the code to print a date-time object with given formatter.
String dateTime = formatter.format(LocalDateTime.now());
System.out.println(dateTime); //2018-Dec-21 11:14:12 
Find the code to parse a date-time object with given formatter.
LocalDateTime ldt = LocalDateTime.parse("2018-Dec-20 08:25:30", formatter);
System.out.println(ldt); //2018-12-20T08:25:30 
Here on this page we will discuss methods of DateTimeFormatter with examples and format LocalDate, LocalDateTime and LocalTime instnaces.

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		
  }
} 
Output
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
  }
} 
Output
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
  }
} 
Output
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); 
Output
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
  }
} 
Output
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); 
Output
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
  }
} 
Output
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); 
Output
08:25:30 

DateTimeFormatter "parse" Methods

DateTimeFormatter provides following methods to parse a text.
1.
TemporalAccessor parse(CharSequence text) 
Parses a text of date, time or date-time and return temporal object.
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)); 
Output
2017
2 
2.
TemporalAccessor parse(CharSequence text, ParsePosition position) 
We can pass 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)); 
Output
2017
2 
3.
<T> T parse(CharSequence text, TemporalQuery<T> query) 
Parses the given text and returns the object specified by 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); 
Output
2017-12-18 
4.
TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) 
Parses the given text and returns one of the specified types.
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); 
Output
2017-12-18 
5.
TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) 
Parses the given text with given 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); 
Output
{DayOfMonth=38, ClockHourOfAmPm=2, MinuteOfHour=46, YearOfEra=2017, SecondOfMinute=41, MonthOfYear=12},null 
6.
static TemporalQuery<Period> parsedExcessDays() 
Provides a query to access excess days as 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		
  }
} 
Output
00:00 , P1D
2018-12-04T00:00 , P0D 
We can see that when we have only time, with time 24:00 (end of day), we get time as 00 and 1 day excess (P1D means period having 1 day). But when we provide date and time both, in that case, excess days are added to date part. We can see in our example that day 3 has become day 4 and excess day is 0.
7.
static TemporalQuery<Boolean> parsedLeapSecond() 
Provides a query to access whether a leap second was parsed. The query returns true if parsing saw a leap second otherwise false. In UTC time-zone, leap seconds occur at '23:59:60'. In other time-zones, time can be different. Find the sample example.
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()));	
  }
} 
Output
2017-12-31T23:59:59Z
leap second parsed=true 
DateTimeFormatter.ISO_INSTANT formats an instant in UTC.

DateTimeFormatter "with" Methods

Following methods return DateTimeFormatter 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);	
  }
} 
Output
Day is:20, month is:12, and year:2018 with the time:11:36 

DateTimeFormatter "get" Methods

We can fetch DateTimeFormatter 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());
  }
} 
Output
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    
  }
} 
Output
Dec 20, 2017
12:34:23 

Predefined Formatters

DateTimeFormatter has following predefined formatters.

FormatterExample
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'
For example we are providing an example to use predefined formatter 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
  }
} 
Output
2018-W51-5
2018-10-04 

Pattern Letters and Symbols

Find the pattern letters and symbols to format date-time.

SymbolDescriptionExample
GeraAD; Anno Domini; A
uyear2018; 18
yyear-of-era2018; 18
Dday-of-year180
M/Lmonth-of-year7; 07; Jul; July; J
dday-of-month11
gmodified-julian-day2451334
Q/qquarter-of-year3; 03; Q3; 3rd quarter
Yweek-based-year1999; 99
wweek-of-week-based-year25
Wweek-of-month3
Eday-of-weekTue; Tuesday; T
e/clocalized day-of-week2; 02; Tue; Tuesday; T
Fday-of-week-in-month2
aam-pm-of-dayAM
hclock-hour-of-am-pm (1-12)12
Khour-of-am-pm (0-110
kclock-hour-of-day (1-24)24
Hhour-of-day (0-23)0
mminute-of-hour35
ssecond-of-minute50
Sfraction-of-second970
Amilli-of-day1234
nnano-of-second987654321
Nnano-of-day1234000000
Vtime-zone IDAmerica/Los_Angeles; Z; -08:30
vgeneric time-zone namePacific Time; PT
ztime-zone namePacific Standard Time; PST
Olocalized zone-offsetGMT+8; GMT+08:00; UTC-08:00
Xzone-offset 'Z' for zeroZ; -08; -0830; -08:30; -083015; -08:30:15
xzone-offset+0000; -08; -0830; -08:30; -083015; -08:30:15
Zzone-offset+0000; -0800; -08:00
ppad next1
'escape for text
''single quote'
[optional section start
]optional section end

References

Class DateTimeFormatter
Java LocalDate
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us