Session 13
Session 13
y
nl
O
se
U
tre
New Date and Time API
en
C
h
ec
pt
rA
Fo
Objectives
y
nl
O
se
U
❖ Explain new classes of the Date and Time API in Java 8
tre
❖ Explain Enum and Clock types
en
❖ Describe the role of time-zones in Java 8
C
❖ Explain support for backward compatibility in the new API
h
ec
pt
rA
Fo
y
New Date-Time API overcomes issues faced by earlier version of date and time library such
nl
as:
O
se
U
tre
en
C
Time-zone
Thread- Poor
h
handling
safe issue design
ec issue
pt
rA
Fo
y
nl
Complete list of classes in API is:
O
LocalDate OffsetTime
se
Clock
Time
U
tre
Duration ZonedDate
LocalTime Period
en
Time
C
h
Instant MonthDay Year
ec
pt ZoneID
rA
Time
y
nl
Clock class in
Java 8 version is used to get the date and time using
O
Clock
current time-zone.
se
U
tre
Clock can beused in the place of System.currentTimeInMillis() and TimeZone.
en
getDefault().
C
h
ec
pt
rA
Fo
y
nl
Following Code Snippet displays the instance of using Clock. It represents
O
Clock how a clock can provide access to the current date and time using a time-
zone.
se
U
tre
import java.time.*; // import the package for Date-Time API classes
…
en
// Creates a new Clock instance based on UTC.
C
…
Clock defaultClock = Clock.systemUTC();
h
System.out.println("Clock : " + defaultClock);
…
ec
pt
// Creates a clock instance based on system clock zone
Clock defaultClock2 = Clock.systemDefaultZone();
rA
y
nl
Following Code Snippet displays how the given date can be verified against
O
Clock
the Clock object:
se
U
public class MyClass {
tre
private Clock clock;
…
en
public void process(LocalDate eventDate) {
if (eventDate.isBefore(LocalDate.now(clock))) {
C
// logic
h
}
}
} ec
pt
rA
Fo
y
nl
Duration class consists of a
group of methods to perform calculations
O
Duration
based on a Duration object.
se
U
plusNanos() plusSeconds() plusHours()
tre
en
minusNanos() minusSeconds() minusHours()
C
h
plusMillis() ec plusMinutes() plusDays()
pt
rA
y
nl
Following Code Snippet shows the usage of plusDays() and minusDays()
O
Duration
methods:
se
U
Duration present = ... // assume code is written to
// get a present duration
tre
Duration samplePlusA = present.plusDays(3);
en
Duration sampleMinusA = present.minusDays(3);
C
Here, first line of code produces a Duration variable, present that will be used as the base of
h
calculations. It is assumed that code to create the Duration object is added.
ec
pt
Code Snippet then produces two new Duration objects based on the present object. The
rA
second line generates a Duration, which is equivalent to present plus three days. The third
Fo
y
Instant
nl
Instant class helps in time stamp creation.
(java.time.instant)
O
se
Generating an Instant:
An instance of an Instant can be generated using one of the Instant class factory methods.
U
tre
Code Snippet shows an Instant object representing the exact moment of now, using method Instant.now().
en
Instant sampleNow = Instant.now();
C
h
Instant Calculations:
ec
Code Snippet displays the use of Instant in nanoseconds and milliseconds.
pt
Instant sampleFuture = sampleNow.plusNanos(4);
rA
y
LocalDate class is bundled with the java.time package.
nl
O
Creating a LocalDate: Obtain a LocalDate:
se
LocalDate objects can be created using
U
To obtain a LocalDate, you can also
several approaches. The first approach is to
create it from a specific year, month, and
tre
get a LocalDate equivalent to the local day information.
date of today.
en
Code Snippet shows creating LocalDate
C
Code Snippet shows creating a LocalDate using of().
object using now().
h
ec
pt
LocalDate sampleLocDaA =
rA
LocalDate sampleLocDaB =
LocalDate.now(); LocalDate.of(2016, 07, 04);
Fo
y
nl
Date information of a LocalDate object can be accessed using following
O
LocalDate
methods:
se
U
getDayOfYear ()
tre
en
C
getDayOfWeek
getYear ()
()
h
ec
pt
getMonth () getDayOfMonth ()
rA
Fo
y
nl
Following Code Snippet illustrates date information of a LocalDate.
O
se
U
int year = localDate.getYear();
int dayOfMonth = localDate.getDayOfMonth();
tre
Month month = localDate.getMonth();
int dayOfYear = localDate.getDayOfYear();
en
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
C
int monthvalue = month.getValue();
h
ec
pt
Notice how getMonth() and getDayOfWeek() methods return an enum instead of an int. These
rA
enums can provide their data as int values by calling their getValue() methods.
Fo
y
nl
LocalDate Calculations:
O
LocalDate A set of date calculations can be achieved with the LocalDate class
se
using one or more of following methods:
U
tre
plusDays () minusDays () plusWeeks () minusWeeks ()
en
C
plusMonths () minusMonths () plusYears ()
h
ec
pt
minusYears ()
rA
Fo
y
nl
LocalDate Calculation Method:
O
Code Snippet displays how a LocalDate calculation methods works.
se
U
tre
In the code, sampleLocDa, a new instance
en
LocalDate sampleLocDa = LocalDate.of(2016,
04, 30); of LocalDate, is created using of()
C
LocalDate sampleLocDaA = method. Then, the code builds a new
sampleLocDa.plusYears(4); LocalDate instance that represents the
h
LocalDate sampleLocDaB = date four years later from the specified date.
sampleLocDa.minusYears(4); ec Finally, the code generates a new
pt
LocalDate instance that denotes the date
rA
y
Represents a local date and time without any time-zone data.
nl
O
Date-Time information of a LocalDateTime object can be accessed using
LocalDateTime
se
getValue() method.
U
Various date and time calculations can be performed on LocalDateTime
tre
object with plus or minus methods.
en
C
Creating a LocalDateTime object based on a specific year, month, and day:
h
ec
LocalDateTime sampleLocDaTiB = LocalDateTime.of (2016, 05, 07, 12, 06, 16, 054);
pt
rA
Parameters passed to of() are year, month, day (of month), hours, minutes, seconds, and
nanoseconds respectively.
Fo
y
nl
Code Snippet illustrates how LocalDateTime calculation methods work.
O
se
LocalDateTime sampleLocDaTi = LocalDateTime.now();
U
LocalDateTime sampleLocDaTiA = sampleLocDaTi.plusYears(4);
LocalDateTime sampleLocDaTiB = sampleLocDaTi.minusYears(4);
tre
en
The code first creates a LocalDateTime instance sampleLocDaTi signifying the current moment.
C
Then, the code creates a LocalDateTime object that denotes a date and time four years later.
h
ec
Finally, the code builds a LocalDateTime object that denotes a date and time four years prior.
pt
rA
Fo
y
nl
LocalTime LocalTime class in Date-Time API signifies exact time of day without any
O
Class time-zone data.
se
Creating a LocalTime Class:
U
tre
en
A LocalTime instance can be generated Another approach to produce a
using several approaches. The foremost LocalTime object is to create it from
C
approach is to create specific hours, minutes, seconds,
h
a LocalTime instance that denotes the and nanoseconds. Code Snippet displays
ec
exact time of now. Code Snippet shows the of() method.
pt
the now() method.
rA
y
nl
LocalTime class consists of a set of methods that can perform local
O
time calculations.
se
LocalTime
Calculations For example, plusMinutes() method adds minutes and
U
minusMinutes() subtracts minutes from a given value in a calculation.
tre
Plus or minus methods are in LocalDateTime object.
Code Snippet explains LocalTime calculations.
en
C
h
ec
LocalTime sampleLocTi = LocalTime.of(12, 24, 33, 00135);
pt
// current local time
rA
y
nl
MonthDay is an immutable Date-Time object that represents month as
O
well as day-of-month.
MonthDay
se
Class
Code Snippet depicts how MonthDay class can be used for checking
U
recurring date-time events.
tre
…
en
// Code to display Birthday wishes
LocalDate dateOfBirth = LocalDate.of(2006, 02, 24);
C
MonthDay bday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.
h
getDayOfMonth());
ec
MonthDay currentMonthDay = MonthDay.from(today); //assume today is defined
if(currentMonthDay.equals(bday)){
pt
System.out.println("**Colorful Joyful Birthday Buddy**");
rA
}
else{
Fo
y
nl
OffsetDateTime is an immutable illustration of date and time with an
O
offset.
Code Snippet displays an example stating California is GMT or
se
OffsetDate
UTC–07:00 and to get a similar time-zone, static method ZoneOffset.of()
U
Time Class
can be used.
tre
After fetching the offset value, OffSetDateTime can be shaped by passing a
en
LocalDateTime and an offset to it.
C
LocalDateTime datetime = LocalDateTime.of(2016, Month.FEBRUARY, 15,
h
ec
18, 20);
// to display the result using Offset
pt
ZoneOffset sampleoffset = ZoneOffset.of("-07:00");
rA
y
OffsetTime class is an immutable Date-Time object that denotes a time,
nl
frequently observed as hour-minute-second-offset.
O
OffsetTime
Class
se
Following Code Snippet shows the complete program to fetch the
U
seconds using the OffsetTime class:
tre
en
import java.time.OffsetTime;// Class to show the result by using Output:
// OffsetTime class method
C
public class MinuteOffset { Minutes: 49
public static void main(String[] args) {
h
ec
OffsetTime d = OffsetTime.now();
int e = d.getMinute();
pt
System.out.println("Minutes: " + e);
rA
}
}
Fo
y
nl
Period (java.time.Period) represents an amount of time in terms of
O
days, months, and years.
se
Period
U
Class Duration and Period are somewhat similar; however, the difference
tre
between the two can be seen in their approach towards Daylight
Savings Time (DST) when they are added to ZonedDateTime.
en
C
h
ec
pt
rA
Fo
y
nl
Period Following Code Snippet displays an example to calculate the span of time
O
Class from today until a birthday, assuming the birthday is on May 22nd:
se
import java.time.LocalDate;// Class to get the present day
U
import java.time.Month; // Class to get month related calculations
tre
import java.time.Period;//Class to calculate the time period between two
//time instances
en
import java.time.temporal.ChronoUnit;
public class NextBday {
C
public static void main(String[] args) {
LocalDate presentday = LocalDate.now();
h
LocalDate bday = LocalDate.of(1983, Month.MAY, 22);
ec
LocalDate comingBDay = bday.withYear(presentday.getYear());
// To address the belated b'day celebration.
pt
if (comingBDay.isBefore(presentday) || comingBDay.isEqual(presentday))
{
rA
comingBDay = comingBDay.plusYears(1);
}
Fo
y
nl
O
System.out.println("Totally, I need to wait for " + waitA.getMonths() + "
months, and " +
se
waitA.getDays() + " days to celebrate my next B'day. (" +
waitB + " days in total)");// to display the waiting time for B'day Bash
U
}
}
tre
en
C
Output:
h
Totally, I need to wait for 0 months and 22 days to celebrate my next
ec
B'day. (22 days in total)
pt
rA
Fo
y
nl
A Year (java.time.Year) object is an immutable Date-Time object that
O
Year Class denotes a year.
se
Following Code Snippet displays the calculations using Year class:
U
tre
import java.time.Year;// Class to use Year values in calculations
en
public class SampleYear {
public static void main(String[] args) {
System.out.println(" The Present Year():"+Year.now());
Output:
C
System.out.println("The year 2002 is a Leap year :"+ The Present Year (): 2016
Year.isLeap(2002));// to display whether the year 2002 is a leap
h
// year or not
The year 2002 is a Leap year:
ec
System.out.println("The year 2012 is a Leap year :"+
Year.isLeap(2012));
false
The year 2012 is a Leap year:
pt
// to display whether the year 2012 is a leap year or not
} true
rA
}
Fo
y
nl
YearMonth (java.time.YearMonth) is a stable Date-Time object that
O
denotes the combination of year and month. This class does not store or
se
denote a day, time, or time-zone. For example, the value 'November
U
2011‘ can be stored in a YearMonth.
YearMonth
tre
YearMonth can be used to denote things such as credit card expiry, Fixed
en
Deposit maturity date, Stock Futures, Stock options expiry dates, or
C
determining if the year is a leap year or not.
h
ec
pt
rA
Fo
y
nl
Following Code Snippet shows the YearMonth calculations:
O
YearMonth
se
U
tre
import java.time.YearMonth;// to use the Year and Month info
public class YearMonth {
public static void main(String[] args) {
en
System.out.println("The Present Year Month:"+YearMonth.now());
Output:
// To display present year and month The Present Year Month: 2016-
C
System.out.println("Month alone:"+YearMonth.parse("2016- 05
04").getMonthValue()); // To display only the month value
h
System.out.println("Year alone:"+YearMonth.parse("2016-04" Month alone: 4
ec
).getYear());// to display the year value alone
System.out.println("This year is a Leap year:"
Year alone: 2016
This year is a Leap year: true
pt
+YearMonth.parse("2016-04").isLeapYear());// leap year check
}
rA
}
Fo
y
nl
ZonedDateTime
O
se
ZonedDateTime(java.time.ZonedDateTime)is an immutable that represents date
U
and time in addition to a time-zone.
tre
The ZonedDateTime class is immutable. This means that all methods executing
en
calculations on a ZonedDateTime object yields a new ZonedDateTime instance.
C
h
ec
pt
rA
Fo
y
ZonedDateTime
nl
O
Following example depicts the usage of methods to get year, month, day, hour, minute,
se
seconds, and zone offset:
U
import java.time.ZonedDateTime;// to access Zoned Date Time
tre
public class ZoneDT {//Class ZoneDT refers to ZonedDateTime
public static void main(String[] args) {
en
Output:
System.out.println(ZonedDateTime.now());
C
ZonedDateTime sampleZoDT = ZonedDateTime.parse("2016-04-
2016-05-
06T06:03:51.787+08:00[Etc
h
03T10:15:30+08:00[Asia/Singapore]");
ec
System.out.println("Present day of the year:"+sampleZoDT.
/UTC]
pt
getDayOfYear()); Present day of the year: 94
System.out.println("Present year:"+sampleZoDT.getYear());
rA
}
Present year: 2016
}
Fo
y
nl
ZoneId is used to recognize rules used to convert between an Instant
ZoneID
O
and a LocalDateTime.
se
U
tre
The two different ID types are as follows:
en
C
h
Fixed offsets
ec
pt
rA
Geographical regions
Fo
y
A time-zone offset is the quantity of time that a time-zone differs from
nl
Greenwich/UTC.
O
se
For example, Berlin is two hours ahead of Greenwich/UTC in Spring and
U
four hours ahead during Autumn.
ZoneOffset
tre
The ZoneId instance for Berlin will reference two ZoneOffset
en
instances - a +02:00 instance for Spring and a +04:00 instance for Autumn.
C
h
Code Snippet illustrates the usage of this class.
ec
pt
ZoneOffset sampleOffset = ZoneOffset.of("+05:00");
rA
Fo
y
Benefits of using Enums in Java:
nl
O
se
U
Enum
Enum
Enum
Enum
tre
Type Safe Has its Used inside New constants
en
own switch can be added
name statements without
C
space breaking the
h
existing code
ec
pt
rA
Fo
y
nl
O
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
se
public class EnumDateCalculation{
public static void main(String args[]){
U
EnumDateCalculation java8enum = new EnumDateCalculation ();
java8enum.enumChromoUnits();
tre
}
public void enumChromoUnits(){
en
// To display the current date
LocalDate today = LocalDate.now();
C
System.out.println("Current date: " + today);
// To display the result 2 weeks addition to the current
h
date
LocalDate nextWeek = today.plus(2, ChronoUnit.WEEKS);
ec
System.out.println("After 2 weeks: " + nextWeek);
// To display the result 2 months addition to the current
pt
date
rA
y
nl
O
date
LocalDate nextYear = today.plus(2, ChronoUnit.YEARS);
System.out.println("After 2 years: " + nextYear);
se
// To display the result 20 years addition to the current
date
U
LocalDate nextDecade = today.plus(2, ChronoUnit.DECADES);
System.out.println("Date after twenty year: " + nextDecade);
tre
}
}
en
C
h
Output:
ec
Current date: 2016-04-07
After 2 weeks: 2016-04-21
pt
After 2 months: 2016-06-07
rA
y
nl
Temporal Adjuster acts as a key tool in modifying the Temporal Object.
O
se
Temporal Adjuster is a A Temporal Adjuster can be For example, it can be used to
U
functional interface that uses used to perform complicated find 'first Thursday of the
tre
adjustInto (Temporal) date 'math' that is popular in month' or 'next Tuesday’.
method to return a copy of business applications.
en
Temporal object with
unchanged field value.
C
h
java.time.temporal ec
Date-Time objects FirstDayOfMonth ( )
pt
rA
Fo
y
nl
Following Code Snippet shows how to find the first day of a month using a specified date:
O
import java.time.LocalDate;
se
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
U
public class TemporalAdj {
tre
public static void main(String args[]){
TemporalAdj TemporalAdj = new TemporalAdj();
en
TemporalAdj.sampleAdj();
}
C
public void sampleAdj(){
h
// To display the current date
ec
LocalDate sampledateA = LocalDate.now();
System.out.println("Current date: " + sampledateA);
pt
// To display the next Wednesday from current date
rA
LocalDate nextWednesday =
sampledateA.with(TemporalAdjusters.next(DayOfWeek.
Fo
WEDNESDAY));
y
nl
System.out.println("Next Wednesday on : " + nextWednesday);
O
// To display the second Sunday of next month
se
LocalDate firstInYear =
LocalDate.of(sampledateA.getYear(),sampledateA.
U
getMonth(), 1);
LocalDate secondSunday = firstInYear.with(TemporalAdjusters.
tre
nextOrSame(DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayOfWeek.
en
SUNDAY));
System.out.println("Second Sunday on : " + secondSunday);
C
}
}
h
ec
pt
Output:
rA
y
nl
O
Date sampleDate = new Date();
se
Instant sampleNow = sampleDate.toInstant();
LocalDateTime dateTime =
U
toInstant()
LocalDateTime.ofInstant(sampleNow, myZone);
tre
ZonedDateTime zdt =
ZonedDateTime.ofInstant(sampleNow, myZone);
en
C
h
ec
In the given code, toInstant() method is being added
Instant,
to the original Date and Calendar objects to convert
ZoneId
pt
them into new Date-Time API.
rA
Fo
y
nl
object.
O
import java.time.LocalDateTime;// to initiate local date and time
se
import java.time.ZonedDateTime; // to initiate zoned time
import java.util.Date;
U
import java.time.Instant;
import java.time.ZoneId;
tre
public class BWCompatibility {
en
public static void main(String args[]){
BWCompatibility bwcompatibility = new BWCompatibility();
C
bwcompatibility.sampleBW();
}
h
public void sampleBW(){
ec
// To display the current date
Date sampleCurDay = new Date();
pt
System.out.println(" Desired Current date= " + sampleCurDay);
rA
// to display result
// To display the instant of current date
Fo
y
LocalDateTime sampleLoDaTi = LocalDateTime.ofInstant(samplenow,
nl
samplecurZone);
O
System.out.println(" Desired Current Local date= " + sampleLoDaTi);
se
// To display result
// To display the desired current zoned date
U
ZonedDateTime sampleZoDaTi = ZonedDateTime.ofInstant(samplenow,
samplecurZone);
tre
System.out.println(" Desired Current Zoned date= " + sampleZoDaTi);
// To display result
en
}
}
C
h
Output:
ec
pt
Desired Current date= Fri May 06 07:32:58 EDT 2016
Desired Current Local date= 2016-05-06T07:32:58.769
rA
04:00[America/New York]
y
nl
Parsing dates from strings and formatting dates to strings is possible with the
O
java.text.SimpleDateFormat class.
se
Code Snippet shows an example of how the SimpleDateFormat class works on
U
java.util.Date instances.
tre
en
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
C
String dateString = format.format( new Date() );
h
Date samplDate = format.parse ("2011-03-25");
ec
pt
rA
Fo
y
TimeZone (java.util.TimeZone) is used in time-zone bound calculations.
nl
O
se
Code Snippet displays a simple Calendar cal = new GregorianCalendar();
example of how to get the time-zone TimeZone tiZo = cal.getTimeZone();
U
from a Calendar.
tre
Code Snippet displays a simple cal.setTimeZone(tiZo);
en
example of how to set time-zone.
C
TimeZone tiZo = TimeZone.getDefault();
h
Code Snippet shows two ways to
ec
obtain a TimeZone instance. OR
TimeZone tiZo =
pt
TimeZone.getTimeZone("Europe/Paris");
rA
Fo
y
nl
O
import java.time.ZonedDateTime;
import java.time.ZoneId;
se
public class Java8CurTZone {
U
public static void main(String args[]){
Java8CurTZone = new Java8CurTZone();
tre
java8curtzone.sampleZDTime(); Output:
}
public void sampleZDTime(){
dateA: 2016-04-03
en
// To display the current date and time T10:15:30+08:00[Asia/Singapore]
ZonedDateTime dateA = ZonedDateTime.parse("2016-04- ZoneId: Asia/Singapore
C
03T10:15:30+08:00[Asia/Singapore]");
System.out.println("dateA: " + dateA); CurrentZone: Etc/UTC
h
// To display the zoneId
ec
ZoneId sampleidA = ZoneId.of("Asia/Singapore");
System.out.println("ZoneId: " + sampleidA);
pt
// To display the current Zone
ZoneId samplecurrentZoneA = ZoneId.systemDefault();
rA
System.out.println("CurrentZone: " +
samplecurrentZoneA);
Fo
}
}
y
nl
unaddressed drawbacks of the previous API.
O
Date-Time API contains many classes to reduce coding complexity and
se
provides various additional features to work on date and time.
U
Enum in Java denotes fixed number of well-known values.
tre
TemporalAdjuster is a functional interface and a key tool for altering a
temporal object.
en
Java TimeZone class is a class that denotes time-zones and is helpful when
C
doing calendar arithmetic across time-zones.
h
Greenwich/UTC. ec
A time-zone offset is the quantity of time that a time-zone differs from
pt
rA
Fo