Java 8 - New Date-Time API
Java 8 - New Date-Time API
With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time
API.
Not thread safe − java.util.Date is not thread safe, thus developers have to deal with
concurrency issue while using date. The new date-time API is immutable and does not
have setter methods.
Poor design − Default Date starts from 1900, month starts from 1, and day starts from 0,
so no uniformity. The old API had less direct methods for date operations. The new API
provides numerous utility methods for such operations.
Difficult time zone handling − Developers had to write a lot of code to deal with timezone
issues. The new API has been developed keeping domain-specific design in mind.
Java 8 introduces a new date-time API under the package java.time. Following are some of the
important classes introduced in java.time package.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
}
import java.time.ZonedDateTime;
import java.time.ZoneId;
ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
date1: 2007-12-03T10:15:30+05:00[Asia/Karachi]
ZoneId: Europe/Paris
CurrentZone: Etc/UTC
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Duration;
import java.time.Period;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
Backward Compatibility
A toInstant() method is added to the original Date and Calendar objects, which can be used to
convert them to the new Date-Time API. Use an ofInstant(Insant,ZoneId) method to get a
LocalDateTime or ZonedDateTime object. Let us see them in action.
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;