0% found this document useful (0 votes)
6 views

DateTime API

Java DateTime API

Uploaded by

Piyush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DateTime API

Java DateTime API

Uploaded by

Piyush Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Advanced Java Programming

Topic: Date Time API

By
Ravi Kant Sahu
Asst. Professor, LPU
Contents…
 Creating and manage date-based events, Creating and manage
time-based events.
 Combining date and time into a single object.
 Working with dates and times across time zones.
 Managing changes resulting from daylight savings.
 Defining and create timestamps, periods and durations.
 Applying formatting to local and zoned dates and times

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why is Date and Time important?
 Need to represent time, used to perform calculation.
 The current date and time. (locally)
 A date and time in future and past.
 Difference between two dates/times in seconds, minutes, hours,
years.
 Date and time in other country.
 Current time after if day light saving is applied.
 Number of days in February(Leap Year).
 A time duration(hours, minutes and seconds) and period(Days,
Month and Years).

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Disadvantages of java.util.Date(Calendar,
TimeZone and DateFormat)
 Does not support fluent API approach.

 Instances are mutable.

 Not thread safe.

 Weakly typed Calendars.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Java Date and Time API goals
 Classes and methods should be straight forward.
 The API should support fluent API approach.
 Instances of Date and Time objects should be immutable.
 Should be thread safe.
 Use ISO standard to define Date and Time.
 API should support strong type checks.
 Allows developers to extend API.
 toString() always returns human readable format.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Working with Local Date and Time
 Java.time package provides two classes for working with local
Date and Time.
 LocalDate
 Does not include time
 A year-month-day representation
 toString – ISO 8601 format(YYYY-MM-DD)

 LocalTime
 Does not include date
 Stores hours:minutes:seconds.nanoseconds
 toString- (HH:mm:ss.SSS)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalDate, LocalTime and LocalDateTime

 They are local in the sense that they represent date and time
from the context of one observer, in contrast to time zones.
 All the core classes in the new API are constructed by
factory methods.
 When constructing a value through its fields, the factory is
called of.
 When converting from another type, the factory is called
from.
 There are also parse methods that take strings as parameters:

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalDate Class

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalDate Class
 A date without a time-zone in the ISO-8601 calendar system,
such as 2007-12-03.

 LocalDate is an immutable date-time object that represents a


date, often viewed as year-month-day.

 Other date fields, such as day-of-year, day-of-week and week-


of-year, can also be accessed.

 This class does not store or represent a time or time-zone so its


portable across time zones.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDate
Methods
 public static LocalDate now()
 public static LocalDate now(ZoneId zone)

 public static LocalDate of(int year, Month month, int


dayOfMonth)
 public static LocalDate of(int year, int month, int dayOfMonth)
 public static LocalDate ofEpochDay(long epochDay)

 public static LocalDate parse(CharSequence text)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDate
Methods
 public int getYear()
 public int getMonthValue()
 public Month getMonth()
 public int getDayOfMonth()
 public int getDayOfYear()
 public DayOfWeek getDayOfWeek()
 public boolean isLeapYear()

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDate
Methods
 public LocalDate with(TemporalAdjuster adjuster)
 public LocalDate withYear(int year)
 public LocalDate withMonth(int month)
 public LocalDate withDayOfMonth(int dayOfMonth)
 public LocalDate withDayOfYear(int dayOfYear)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDate
Methods
 public LocalDate plusYears(long yearsToAdd)
 public LocalDate plusMonths(long monthsToAdd)
 public LocalDate plusWeeks(long weeksToAdd)
 public LocalDate plusDays(long daysToAdd)

 public LocalDate minusYears(long yearsToSubtract)


 public LocalDate minusMonths(long monthsToSubtract)
 public LocalDate minusWeeks(long weeksToSubtract)
 public LocalDate minusDays(long daysToSubtract)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exercise

 WAP which prompts the user to enter the date of birth and now
display the Day on which the user was born?

 Also print on which Day his 21st B’day falls.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
TemporalAdjusters
 TemporalAdjuster object can be obtained using the methods of
TemporalAdjusters class.

Methods:
 public static TemporalAdjuster firstDayOfNextYear()
 public static TemporalAdjuster firstInMonth(DayOfWeek
dayOfWeek)
 public static TemporalAdjuster lastInMonth(DayOfWeek
dayOfWeek)
 public static TemporalAdjuster next(DayOfWeek dayOfWeek)
 public static TemporalAdjuster previous(DayOfWeek
dayOfWeek)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Let’s Do Something….

 WAP which prompts the user to enter a Date using command-


line argument and the number of year, months and days.

 Now find out the Day after that many Day, year and month
from the entered Date.

 Find the First Monday in the next year.

 Find the Date on Previous Friday.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalTime Class

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalTime Class
 A time without a time-zone in the ISO-8601 calendar system,
such as 10:15:30. 13

 LocalTime is an immutable date-time object that represents a


time, often viewed as hour-minute-second.

 Time is represented to nanosecond precision.


 For example, the value "13:45:30.123" can be stored in a
LocalTime.

 This class does not store or represent a date or time-zone.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalTime
Methods
 public static LocalTime now()
 public static LocalTime now(ZoneId zone)

 public static LocalTime of(int hour, int minute)


 public static LocalTime of(int hour, int minute, int second)
 public static LocalTime of(int hour, int min, int sec, int nsec)

 public static LocalTime parse(CharSequence text)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalTime
Methods
 public int getHour()
 public int getMinute()
 public int getSecond()
 public int getNano()

 public boolean isAfter(LocalTime l)


 public boolean isBefore(LocalTime l)

 public LocalDateTime atDate(LocalDate d)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalTime

Methods
 public LocalTime with(TemporalAdjuster adjuster)
 public LocalTime withHour(int hour)
 public LocalTime withMinute(int min)
 public LocalTime withSecond(int sec)
 public LocalTime withNano(int ns)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalTime
Methods
 public LocalTime plusHours(long hours)
 public LocalTime plusMinutes(long min)
 public LocalTime plusSeconds(long sec)
 public LocalTime plusNanos(long ns)

 public LocalTime minusHours(long hours)


 public LocalTime minusMinutes(long min)
 public LocalTime minusSeconds(long sec)
 public LocalTime minusNanos(long ns)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalDateTime Class

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
LocalDateTime Class
 A date-time without a time-zone in the ISO-8601 calendar
system, such as 2007-12-03T10:15:30.

 LocalDateTime is an immutable date-time object that


represents a date-time, often viewed as year-month-day-hour-
minute-second.
 Other date and time fields, such as day-of-year, day-of-week
and week-of-year, can also be accessed.

 Time is represented to nanosecond precision.


 For example, the value "2nd October 2007 at
13:45.30.123456789" can be stored in a LocalDateTime.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDateTime
Methods
 public static LocalDateTime now()
 public static LocalDateTime now(ZoneId zone)

 public static LocalDateTime of(int year, int mnth, int day, int
hour, int mint)
 public static LocalDateTime of(int year, int mnth, int day, int
hour, int mint, int sec)
 public static LocalDateTime of(int year, int mnth, int day, int
hour, int mint, int sec, int nsec)
 public static LocalDateTime of(LocalDate d, LocalTime t)
 public static LocalDateTime parse(CharSequence text)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDateTime
Methods
 public int getHour()
 public int getMinute()
 public int getSecond()
 All other getter methods of LocalDate and LocalTime class

 public LocalDateTime plusHours(long hours)


 public LocalDateTime plusMinutes(long min)
 public LocalDateTime minusHours(long hours)

 All the plus and minus methods of LocalDate and LocalTime


class
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of LocalDateTime

Methods
 public LocalDate toLocalDate()
 public LocalTime toLocalTime()

 public LocalDateTime withYear(int y)


 public LocalDateTime withHour(int hr)
 All the with methods of LocalDate andLocalTime class

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Instant

 An instant is a point of time counting from the first


second of 1/1/1970, also known as epoch.

 Instants after the epoch have positive values, and


earlier instants have negative values.

 An Instant can be created in a similar way as a date or


a time:

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using Instant

Instant n = Instant.now();
Instant epochNow =
Instant.ofEpochSecond(1000000);

long s = n.getEpochSecond();
int ns = n.getNano();
Instant twoSecondsAfter = n.plusSeconds(2);
Instant twoSecondsBefore = n.minusSeconds(2);

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Period
 A period represents a value such as "1 months and 15
days", in contrast to the other classes that represent a point
in time.

 Period period = Period.of(1, 2, 3); // 1 year, 2 months, 3


days

 Period period2 = Period.ofMonths(2);


 Period period20142015 =
Period.between(LocalDate.of( 2014, Month.JANUARY,
1), LocalDate.of( 2015, Month.JANUARY, 1));
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using Period
 int y = period.getYears();
 Period newPeriod = period.plusDays(2).minusMonths(1);

NOTE:
 We can modify the values of dates using periods:

LocalDate newDate = date.plus(period);

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Duration

 A duration is similar to a period but its precision is


based on hours, minutes, seconds, milliseconds.

 A duration can be created using an amount of seconds


or minutes or hours or by specifying start and end
times:

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Duration
 A duration is similar to a period but its precision is based on
hours, minutes, seconds, milliseconds.

 A duration can be created using an amount of seconds or


minutes or hours or by specifying start and end times:

 Duration d2 = Duration.ofSeconds(10, 50); // 10 seconds and


50 nanoseconds

 Duration d2 = Duration.between(LocalTime.NOON,
LocalTime.MIDNIGHT);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Working with dates and
times across time zones

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
TImezones and DayLight
Saving

The world is divided into many different timezones. As well as


different countries being in one or more different timezones,
some countries also apply Daylight Saving Time (DST).

DST is a system of handling the changing amounts of daylight


throughout the year, as the seasons change.

In any given timezone, as you get further away from the equator,
there are more hours of daylight per day in summer than there
are in winter. So, the goal of DST is to maximize the daylight
hours available during typical waking hours.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DayLight Saving
By adjusting clocks forward on a specific date by a standard
amount, usually one hour, people can take better advantage of
daylight during their typical working day.

For example, suppose you wake daily at 7:00 AM. In the spring,
the sun rises earlier each day. So, instead of waking up at 6:00
AM to take advantage of the extra daylight, DST observers
move their clocks ahead by one hour.

The effect is that they can continue to wake at 7:00 AM


according to the clock and also enjoy more daylight. In the fall,
clocks are set back an hour as sunrise happens later each day.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DayLight Saving

Since DST policy is set by national and regional governments,


changes in DST policy occur at different times in different
countries.
Some countries are currently extending their DST periods,
thereby changing the dates on which DST will come into effect
in a given year.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DateTimeFormatter

 java.time.format.DateTimeFormatter class is used for


printing and parsing date-time objects.

 This class works by using:


Predefined constants, such as ISO_LOCAL_DATE
Pattern letters, such as yyyy-MMM-dd
Localized styles, such as long or medium

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DateTimeFormatter

LocalDate date = LocalDate.now();

DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(“dd/MM/yyyy");

String text = date.format(formatter);

System.out.println(“Date in dd/MM/yyyy Format” + text);

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DateTimeFormatter

System.out.println(“Enter the Date in dd-MM-yyyy Format”);


String date = sc.nextLine();

DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(“dd-MM-yyyy");

LocalDate ld = LocalDate.parse(date, formatter);

System.out.println(“Date entered is: ” + ld);

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Date/Time Formatting
 The date-time classes provide two methods - one for
formatting and one for Parsing.
Formatting Example:
LocalDateTime dt =
LocalDateTime.of( 2010, Month.JULY, 03, 09, 0, 30 );
String isoDateTime =
dt.format(DateTimeFormatter.ISO_DATE_TIME);

Parsing Example:
LocalDate dt = LocalDate.parse("2014/09/19 14:05:12",
DateTimeFormatter.ofPattern( "yyyy/MM/dd kk:mm:ss" ) );

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ZonedDateTime

 ZonedDateTime is an immutable representation of a


date-time with a time-zone.

 This class stores all date and time fields, to a precision


of nanoseconds, and a time-zone, with a zone offset
used to handle ambiguous local date-times.

 2022-03-31T10:15:30+01:00 Europe/Paris

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods
 public static ZonedDateTime now()

 public static ZonedDateTime now(ZoneId zone)

 public static ZonedDateTime of(LocalDate date, LocalTime


time, ZoneId zone)

 public static ZonedDateTime of(LocalDateTime localDateTime,


ZoneId zone)

 public static ZonedDateTime parse(CharSequence text)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

You might also like