New Date -Time API in Java 8
Java 8 introduced a new Date and Time API under the package java.time to overcome the limitations of the old java.util.Date and java.util.Calendar classes. Previously it was challenging to work with date and time in the Java project. The old APIs had several issues. To overcome this, The new java.time API was introduced in Java 8 to solves these by being immutable, type-safe, and comprehensive.
Why a New Date-Time API?
- Not thread-safe → objects could be modified, causing concurrency problems.
- Confusing design → Mixed handling of date, time, and time zones.
- Limited functionality → Few operations for manipulating dates and times.
- Poor readability → Months were zero-based, leading to errors.
Key Benefits:
- Immutable & thread-safe → Safe for concurrent use.
- Clear separation of date, time, and time zone.
- Rich API for calculations (add/subtract days, months, etc.).
- Better formatting/parsing with .
- Interoperability with legacy via conversion methods.
Core Classes in Java Time API:
- Local API - Represent date/time without time zone.
- Zoned API - Handle time zones and offsets.
- Instant - Represents a timestamp (machine time).
- Period/Duration - Represent date-based (years, months, days) and time-based (hours, minutes, seconds) amounts.
- Temporal Units - Type-safe units like DAYS, WEEKS, YEARS.
- Formatter - Parsing and formatting dates/times.
For Example:
import java.time.*;
public class DateTimeDemo {
public static void main(String[] args) {
// Current date and time
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
// Specific date
LocalDate independenceDay = LocalDate.of(1947, Month.AUGUST, 15);
// Adding days
LocalDate nextWeek = date.plusWeeks(1);
// Working with time zones
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
// Duration between two times
Duration duration = Duration.between(time, time.plusHours(2));
System.out.println("Today: " + date);
System.out.println("Independence Day: " + independenceDay);
System.out.println("Next Week: " + nextWeek);
System.out.println("Zoned Time: " + zoned);
System.out.println("Duration: " + duration);
}
}
More...
Interfaces in Java
#Tags: | Java | Java Inheritance | Java Methods | Java Questions | Java FAQs | Java questions and answers |
*Disclaimer: We have published the above images and information for reference purpose only, for any changes on the content we refer to visit the Official Website to get the latest info.
NOTE: Free Career Hub Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.