0% found this document useful (0 votes)
54 views35 pages

New Date and Time API: Session: 13

The document discusses the new Date and Time API introduced in Java 8. It explains the key classes like LocalDate, LocalTime, Instant, Clock and how they can be used to work with dates, times and perform calculations. It provides details on each class through code examples.

Uploaded by

Le Doan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views35 pages

New Date and Time API: Session: 13

The document discusses the new Date and Time API introduced in Java 8. It explains the key classes like LocalDate, LocalTime, Instant, Clock and how they can be used to work with dates, times and perform calculations. It provides details on each class through code examples.

Uploaded by

Le Doan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Session: 13

New Date and Time API


Objectives

❖ Explain new classes of the Date and Time API in Java 8


❖ Explain Enum and Clock types
❖ Describe the role of time-zones in Java 8
❖ Explain support for backward compatibility in the new API

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 2


Introduction

New Date-Time API overcomes issues faced by earlier version of date and time library such
as:

Time-zone
Thread- Poor
handling
safe issue design
issue

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 3


Classes in New Date and Time API 1/29
java.time package acts as a repository where all classes of new Date and Time API are
located. Complete list of classes in API is:

Lo calDate OffsetTime
Clock
Time

Du ZonedDate
LocalTime Period
ration Time

Instant MonthDay Year


ZoneID

OffsetDate YearMonth ZoneOffset


LocalDate
Time

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 4


Classes in New Date and Time API 2/29

Clock
Clock class in Java 8 version is used to get the date and time using
current time-zone.

Clock can be used in the place of System.currentTimeInMillis() and


TimeZone.
getDefault().

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 5


Classes in New Date and Time API 5/29

Duration class consists of a group of methods to perform


Duration
calculations based on a Duration object.

plusNanos() plusSeconds() plusHours()

minusNanos() minusSeconds() minusHours()

plusMillis() plusMinutes() plusDays()

minusMillis() minusMinutes() minusDays()

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 6


Classes in New Date and Time API 6/29

Duration
Following Code Snippet shows the usage of plusDays() and minusDays()
methods:

Duration present = ... // assume code is written to


// get a present duration
Duration samplePlusA = present.plusDays(3);
Duration sampleMinusA = present.minusDays(3);

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 7


Classes in New Date and Time API 7/29

Instant
(java.time.instant)
Instant class helps in time stamp
creation.
Generating an Instant:
An instance of an Instant can be generated using one of the Instant class factory methods.

Code Snippet shows an Instant object representing the exact moment of now, using method Instant.now().

Instant sampleNow = Instant.now();

Instant Calculations:
Code Snippet displays the use of Instant in nanoseconds and
milliseconds.

Instant sampleFuture = sampleNow.plusNanos(4);


// four nanoseconds in the future
Instant samplePast = sampleNow.minusNanos(4);
//four nanoseconds in the past
© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 8
Classes in New Date and Time API 8/29
LocalDate class is bundled with the java.time
package.
Creating a LocalDate: Obtain a LocalDate:
LocalDate objects can be created using
several approaches. The first approach is to To obtain a LocalDate, you can also
create it from a specific year, month, and
get a LocalDate equivalent to the day information.
local date of today.
Code Snippet shows creating
Code Snippet shows creating a LocalDate
LocalDate using of().
object using now().

LocalDate sampleLocDaA = LocalDate sampleLocDaB =


LocalDate.now(); LocalDate.of(2016, 07, 04);

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 9


Classes in New Date and Time API 9/29

Date information of a LocalDate object can be accessed using


LocalDate
following
methods:

getDayOfYear ()

getDayOfWeek
getYear ()
()

getMonth getDayOfMonth
() ()

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 10


Classes in New Date and Time API 10/29
Following Code Snippet illustrates date information of a LocalDate.

LocalDate localDate = LocalDate.now();

int year = localDate.getYear();


int dayOfMonth = localDate.getDayOfMonth();
Month month = localDate.getMonth();
int dayOfYear = localDate.getDayOfYear();
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int monthvalue = month.getValue();

Notice how getMonth() and getDayOfWeek() methods return an enum instead of an int. These
enums can provide their data as int values by calling their getValue() methods.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 11


Classes in New Date and Time API 11/29

LocalDate Calculations:
LocalDate A set of date calculations can be achieved with the LocalDate
class
using one or more of following methods:

plusDays () minusDays () plusWeeks () minusWeeks ()

plusMonths minusMonths () plusYears ()


()

minusYears
()

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 12


Classes in New Date and Time API 13/29

Represents a local date and time without any time-zone data.

Date-Time information of a LocalDateTime object can be accessed


LocalDateTime using
getValue() method.
Various date and time calculations can be performed on LocalDateTime
object with plus or minus methods.

Creating a LocalDateTime object based on a specific year, month, and day:


LocalDateTime sampleLocDaTiB = LocalDateTime.of (2016, 05, 07, 12, 06, 16, 054);
Parameters passed to of() are year, month, day (of month), hours, minutes, seconds, and
nanoseconds respectively.

LocalDateTime sampleLocDaTi = LocalDateTime.now();


LocalDateTime sampleLocDaTiA = sampleLocDaTi.plusYears(4);
LocalDateTime sampleLocDaTiB = sampleLocDaTi.minusYears(4);
© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 13
Classes in New Date and Time API 15/29

LocalTime LocalTime class in Date-Time API signifies exact time of day without
Class any
time-zone data.
Creating a LocalTime Class:

A LocalTime instance can be Another approach to produce a


generated using several approaches. LocalTime object is to create it
The foremost approach is to create from specific hours, minutes,
a LocalTime instance that denotes the seconds,
exact time of now. Code Snippet shows and nanoseconds. Code Snippet displays
the now() method. the of() method.

Code Snippet: Code Snippet:


LocalTime sampleLocTiA = LocalTime sampleLocTiB =
LocalTime.now(); LocalTime.of(12, 24, 33, 00135);
© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 14
Classes in New Date and Time API 16/29

 LocalTime class consists of a set of methods that can perform


local time calculations.
LocalTime
 For example, plusMinutes() method adds minutes and
Calculation minusMinutes() subtracts minutes from a given value in a
s calculation.
 Plus or minus methods are in LocalDateTime object.
 Code Snippet explains LocalTime calculations.

LocalTime sampleLocTi = LocalTime.of(12, 24, 33, 00135);


LocalTime sampleLocTiFuture = sampleLocTi.plusHours(4);// future
LocalTime sampleLocTiPast = sampleLocTi.minusHours(4);// past

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 15


Classes in New Date and Time API 17/29

 MonthDay is an immutable Date-Time object that represents month as


well as day-of-month.
MonthDay
Class  Code Snippet depicts how MonthDay class can be used for
checking recurring date-time events.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 16


Classes in New Date and Time API 18/29

 OffsetDateTime is an immutable illustration of date and time with an


offset.
OffsetDate
Time
 Code Snippet displays an example stating California is GMT or
Class UTC–07:00 and to get a similar time-zone, static method ZoneOffset.of()
can be used.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 17


Classes in New Date and Time API 19/29
 OffsetTime class is an immutable Date-Time object that denotes a
OffsetTime
Class time,
frequently observed as hour-minute-second-offset.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 18


Classes in New Date and Time API 20/29

 Period (java.time.Period) represents an amount of time in terms


of
Period days, months, and years.
Class  Duration and Period are somewhat similar; however, the difference
between the two can be seen in their approach towards Daylight
Savings Time (DST) when they are added to ZonedDateTime.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 19


Classes in New Date and Time API 21/29
Period Following Code Snippet displays an example to calculate the span of time
Class from today until a birthday, assuming the birthday is on Jan 13rd:

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 20


Classes in New Date and Time API 23/29

Year  A Year (java.time.Year) object is an immutable Date-Time object


Class that denotes a year.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 21


Classes in New Date and Time API 24/29

YearMonth (java.time.YearMonth) is a stable Date-Time object that


denotes the combination of year and month. This class does not store or
denote a day, time, or time-zone. For example, the value 'November
2011‘ can be stored in a YearMonth.
YearMonth
YearMonth can be used to denote things such as credit card expiry,
Fixed Deposit maturity date, Stock Futures, Stock options expiry dates,
or determining if the year is a leap year or not.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 22


Classes in New Date and Time API 26/29
ZonedDateTime
ZonedDateTime(java.time.ZonedDateTime)is an immutable that
represents date and time in addition to a time-zone.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 23


Classes in New Date and Time API 28/29

ZoneId is used to recognize rules used to convert between an


ZoneID
Instant
and a LocalDateTime.

The two different ID types are as follows:

Fixed offsets

Geographical regions

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 24


Classes in New Date and Time API 29/29
A time-zone offset is the quantity of time that a time-zone differs from
Greenwich/UTC.

For example, Berlin is two hours ahead of Greenwich/UTC in Spring and


four hours ahead during Autumn.
ZoneOffset
The ZoneId instance for Berlin will reference two ZoneOffset
instances - a +02:00 instance for Spring and a +04:00 instance for
Autumn.

Code Snippet illustrates the usage of this class.


ZoneOffset sampleOffset = ZoneOffset.of("+05:00");

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 25


Enums In Java 8 1/3
Benefits of using Enums in Java:
Enum

Enum
Enum

Enum
Type Safe Has its Used inside New constants
own switch can be added
name statements without
space breaking the
existing code

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 26


Enums In Java 8 2/3
ChronoUnit enumeration is used in following Code Snippet:

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 27


Temporal Adjusters 1/3

Temporal Adjuster acts as a key tool in modifying the Temporal Object.

Temporal Adjuster is a A Temporal Adjuster can be For example, it can be used to


functional interface that uses used to perform complicated find 'first Thursday of
adjustInto (Temporal) date 'math' that is popular in month' or 'next Tuesday’.
the
method to return a copy of business applications.
Temporal object with
unchanged field value.

java.time.temporal Date-Time objects FirstDayOfMonth


( )

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 28


Temporal Adjusters 2/3
Following Code Snippet shows how to find the first day of a month using a specified date:

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 29


Backward Compatibility with Older Versions 1/3

Date sampleDate = new Date();


Instant sampleNow = sampleDate.toInstant();
LocalDateTime dateTime =
toInstant()
LocalDateTime.ofInstant(sampleNow, myZone);
ZonedDateTime zdt =
ZonedDateTime.ofInstant(sampleNow, myZone);

In the given code, toInstant() method is being


Instant,
added to the original Date and Calendar objects to
ZoneId
convert them into new Date-Time API.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 30


Backward Compatibility with Older Versions 2/3
ofInstant(Instant, ZoneId) method is used to get a LocalDateTime or ZonedDateTime
object.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 31


Parsing and Formatting Dates

Parsing dates from strings and formatting dates to strings is possible with the
java.text.SimpleDateFormat class.

Code Snippet shows an example of how the SimpleDateFormat class works


on
java.util.Date instances.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");


String dateString = format.format( new Date() );
Date samplDate = format.parse ("2011-03-25");

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 32


TimeZone (java.util.TimeZone) 1/2

TimeZone (java.util.TimeZone) is used in time-zone bound calculations.

Code Snippet displays a simple Calendar cal = new GregorianCalendar();


example of how to get the time-zone TimeZone tiZo = cal.getTimeZone();
from a Calendar.

Code Snippet displays a simple cal.setTimeZone(tiZo);


example of how to set time-zone.

Code Snippet shows two ways to TimeZone tiZo = TimeZone.getDefault();


obtain a TimeZone instance. OR
TimeZone tiZo =
TimeZone.getTimeZone("Europe/Paris");

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 33


TimeZone (java.util.TimeZone) 2/2
Following Code Snippet shows a sample of time-zone:

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 34


SUMMARY
 The new Date-Time API introduced in Java 8 is a solution for
many unaddressed drawbacks of the previous API.
 Date-Time API contains many classes to reduce coding complexity
and provides various additional features to work on date and time.
 Enum in Java denotes fixed number of well-known values.
 TemporalAdjuster is a functional interface and a key tool for altering
a
temporal object.
 Java TimeZone class is a class that denotes time-zones and is helpful when
doing calendar arithmetic across time-zones.
 A time-zone offset is the quantity of time that a time-zone differs
from Greenwich/UTC.

© Aptech Ltd. Fundamental Programming in Java -Session 13 / Slide 35

You might also like