Java 8 introduced a replacement for the old date and time classes existing in the java.util.Date
package: the new java.time
package, based on the Joda-Time project, designed for multiple calendar systems (the default is the ISO8601) and supporting time zone, duration, format and parsing.
The four java.time
classes you must know for the exam are:
LocalDate
: date without timeLocalTime
: time without dateLocalDateTime
: date and timeZonedDateTime
: date and time including zone info
In this post, we will refer to these classes as the four calendar classes.
The TemporalAccessor Interface
The four calendar classes have no hierarchy relationship among themselves, but they all implement the TemporalAccessor
interface, that represents an arbitrary and read-only set of date and time information. This interface allows reading, in a uniform way, the individual information fields of the date and time objects:
TemporalAccessor Main Methods |
|
---|---|
int get(TemporalField field) |
Gets the value of the specified field |
boolean isSupported(TemporalField field) |
Checks if the specified field is supported. |
The following example shows how to use these methods:
1 2 3 4 5 6 7 8 9 10 |
// creates a calendar object (current date and time) LocalDateTime now = LocalDateTime.now(); // ChronoField is an enum than implements TemporalField // Using ChronoField's constants we can read calendar info: now.get(ChronoField.YEAR); now.get(ChronoField.DAY_OF_WEEK); now.get(ChronoField.MINUTE_OF_DAY); |
Creating Date and Time Objects
The four calendar classes are immutable and have no public constructors. You must use static methods like of
and from
to create instances of these four classes:
LocalDate Main Methods |
|
---|---|
static LocalDate of(int year, int month, 
int dayOfMonth) |
Creates an instance of LocalDate from the given data |
static LocalDate from(TemporalAccessor t) |
Creates an instance of LocalDate from another |
LocalTime Main Methods |
|
static LocalTime of(int hour, int minute 
[, int second]) |
Creates an instance of LocalTime from the given data |
static LocalTime from(TemporalAccessor t) |
Creates an instance of LocalTime from another |
LocalDateTime Main Methods |
|
static LocalDateTime of(int year, int month, 
int dayOfMonth, int hour,int minute 
[, int second]) |
Creates an instance of LocalDateTime from the provided data |
static LocalDateTime from(TemporalAccessor t) |
Creates an instance of LocalDateTime from another |
ZonedDateTime Main Methods |
|
static ZonedDateTime of(int year, int month, 
int dayOfMonth, int hour, int minute, 
int second, int nanosecond, ZoneId zone) |
Creates an instance of ZonedDateTime from the provided data |
static ZonedDateTime of(LocalDate date, 
LocalTime time, ZoneId zone) |
Creates an instance of ZonedDateTime from a LocalDate and a LocalTime |
static ZonedDateTime of( 
LocalDateTime localDateTime, ZoneId zone) |
Creates an instance of ZonedDateTime from a LocalDateTime object |
static ZonedDateTime from(TemporalAccessor t) |
Creates an instance of ZonedDateTime from another |
Most of the previous methods throw a DateTimeException
if they are unable to convert (e.g. there is no enough info in a LocalDate
to create a LocalTime
) or if any of the arguments is not valid (e.g. month out of range) .
Formatting and Parsing
The four classes provide the same two methods for formatting and parsing:
Calendar Classes: Formatting and Parsing Methods | |
---|---|
String format(DateTimeFormatter formatter) |
Converts the calendar object to a String |
static LocalDate parse(CharSequence text, DateTimeFormatter formatter) |
Creates a calendar object (LocalDate in this case) from a CharSequence |
The DateTimeFormatter
object specifies how the conversions are made. You can create your own formatters, but most often you will use any of the predefined constants provided by DateTimeFormatter
. The table below shows a sample of these constants (you don’t have to know all of them for the exam but it never hurts to take a look at the official javadoc and get familiar with them).
Predefined Formatters Sample (DateTimeFormatter constants) |
||
---|---|---|
ISO_DATE |
ISO Date with or without offset | 1968-05-10+01:00; 
1968-05-10 |
ISO_LOCAL_DATE |
ISO Local Date | 1968-05-10 |
ISO_LOCAL_DATE_TIME |
ISO Local Date and Time | 1968-05-10T22:30:00 |
ISO_LOCAL_TIME |
Time without offset | 22:30:00 |
ISO_ZONED_DATE_TIME |
Zoned Date Time | 1968-05-10T22:30:00 
+01:00[Europe/Paris] |
The calendar object you are formatting must contain all the fields (date, time and zone) required by the chosen formatter or an exception will be thrown:
1 2 3 4 5 6 7 8 9 10 |
// create a calendar object with date and time info LocalDateTime ldt = LocalDateTime.of(1968, 5, 10, 22, 30, 0); // to format this object we need an appropriate formatter (date and time) String s = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // this prints "1968-05-10T22:30:00" System.out.println(s); |
In addition to the format
and parse
methods in the four calendar classes, DateTimeFomatter
provides similar methods for parsing and formatting:
DateTimeFormatter Methods |
|
---|---|
String format(TemporalAccesor temporal) |
Converts the calendar object to a String |
TemporalAccesor parse(CharSequence text) |
Creates a calendar object from a string |
Notice that in this case TemporalAccessor
is used for parameter and return types:
1 2 3 4 5 6 7 8 9 10 |
// create a calendar object with date and time info TemporalAccessor ldt = LocalDateTime.of(1968, 5, 10, 22, 30, 0); // format the calendar object String s = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ldt); // this prints "1968-05-10T22:30:00" System.out.println(s); |
Period and Duration
The Period
class is used to specify an amount of time in terms of years, months and days. Negative values are allowed as you can see in the examples below:
1 2 3 4 5 6 7 |
Period p1 = Period.of(0, 2, 7); // 2 months and 7 days Period p2 = Period.of(1, 2, 7); // 1 year, 3 months and 7 days Period p3 = Period.ofDays(7); // 7 days Period p4 = Period.ofWeeks(5); // 5 weeks Period p5 = Period.ofMonths(-2); // -2 months |
The Duration
class is used to specify an amount of time in terms of hours, minutes, and seconds:
1 2 3 4 5 6 7 |
Duration d1 = Duration.of(2, ChronoUnit.HOURS); // 2 hours Duration d2 = Duration.of(45, ChronoUnit.MINUTES); // 45 minutes Duration d3 = Duration.ofHours(2); // 2 hours Duration d4 = Duration.ofMinutes(5); // 5 minutes Duration d5 = Duration.ofSeconds(-30); // -30 seconds |
Both classes implement the TemporalAmount
interface, so they can be used to modify calendar objects (e.g. adding or subtracting a concrete amount of time):
1 2 3 4 5 6 7 8 9 10 |
LocalDateTime ldt = LocalDateTime.of(1968, 5, 10, 22, 30, 0); Period p = Period.ofDays(7); // create a new calendar object (ldt + 7 days) LocalDateTime seeYouInAWeek = ldt.plus(p); // create a new calendar object (ldt - 7 days) LocalDateTime oneWeekAgo = ldt.minus(p); |