Core Java

OCA Java 8 Preparation : DateTimeFormatter

Introduction :

DateTimeFormatter class belongs to java.time.format package. You can use it to format or parse the date or time or a datetime object. Remember for the sake of exam, it defines rules for both parsing and formatting.

To instantiate a DateTimeFormatter, use any of the below ways :

  1. Calling the static ofLocalizedXXX() method, passing it the FormatStyle value.
  2. By using the public static fields defined in DateTimeFormatter.
  3. By invoking static method ofPattern(), passing it a string value describing the object pattern.

ofLocalizedXXX() Methods :

When using ofLocalizedXXX() methods, use below tables for identifying valid FormatStyle values and their output. For any invalid FormatStyle, for instance passing a FormatStyle.LONG for a time based value will throw a DateTimeException.

FormatStyleExample
FormatStyle.FULLSunday, February 4, 2018
FormatStyle.LONG February 4, 2018
FormatStyle.MEDIUM Feb 4, 2018
FormatStyle.SHORT4/2/18
Table 1 : Valid FormatStyle for date-based values

 

FormatStyleExample
FormatStyle.MEDIUM3:45:45 PM
FormatStyle.SHORT3:45 PM
Table 2 : Valid FormatStyle for time-based values

 

Below are few examples of instantiating the formatter using ofLocalizedXXX() method.It is important to note that it formats the date and time objects according to the default locale of the system on which the code executes. So the output might vary slightly across systems.

Using class-level fields :

The other way to instantiate a DateTimeFormatter is to use the available class level fields(public and static) . Below are the available formatters, you need to know.

Sample usage :

Using ofPattern() method :

You can chose to pass in the expected pattern as a string argument to this method to instantiate the DateTimeFormatter.

You can use letters from the below table to define a pattern.

Component DescriptionPattern SymbolExamples
Year
Proleptic year: 'u' symbol is used.
Year of Era(AD/BC) : use 'y'
u
uu
uuu
uuuu
uuuuu
2018
18(2 right-most digits)
2018
2018
02018(left-padding)
Era(AD or BC)indicator
Use it when using 'Year of Era'(y) Symbol for representing the year
GAD
Month in yearM
MM
MMM
MMMM
9
09
Sep
September
Day in monthd
dd
5
05
Day name in a weekE
EE
EEE
EEEE
Wed
Wed
Wed
Wednesday
Hour in a day(Range is 0-23)


Hour in a day(in range -0-12)
Note: Must use AM/PM marker in this case, needed for parsing
H
HH

h
hh
3
03

3
03
Minute in an hour(Range : 0-59)m
mm
8
08
Second in a minute(Range : 0-59)s
ss
9
09
Fraction of a second(Milliseconds)SSS
SSSSSS
SSSSSSSSS
234
142431
152453222
AM/PMaPM
Table : DateTimeFormatter Pattern Symbols

Using DateTimeFormatter for Formatting :

Once we have learnt how to instantiate a DateTimeFormatter, let’s see how can we use it to format the temporal objects. To do so, you can either use the format() method from that temporal class(say LocalDate, LocalTime, LocalDateTime) or use the format() method from DateTimeFormatter class.

TemporalAccessor, referred above, is an interface, implemented by the temporal classes – LocalDate, LocalTime and LocalDateTime.Refer some example usages.

Make sure that you are using a valid formatter over a temporal object, an attempt to violate this law will produce a UnSupportedTemporalTypeException. For instance, if I am trying to use a DateTimeFormatter designed to handle date objects over the LocalTime instance, my code will throw a runtime exception.

Parsing Using DateTimeFormatter :

The below available methods can be used for parsing a temporal object.

When using the parse(charSeq) method from temporal classes(denoted by I. in the above snippet) , the parsing is achieved using the default DateTimeFormatter instance i.e. DateTimeFormatter.ISO_LOCAL_DATE for LocalDate, DateTimeFormatter.ISO_LOCAL_TIME for LocalTime, and DateTimeFormatter.ISO_LOCAL_DATE_TIME for LocalDateTime.

Below are some example usages of these methods :

Conclusion :

In this post, we covered DateTimeFormatter class, the ways of instantiating it and how to parse and format temporal objects using the instance of DateTimeFormatter.

Note : We have already covered LocalDate, LocalTime, LocalDateTime and Period classes of Java Date Time API in our previous posts. Please feel free to check them out.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *