Date and Time API in Java 8
The java.time package, added in Java 8 (JEP 150), is the modern Date and Time API. It replaces most uses of java.util.Date and Calendar with clear, immutable and thread-safe types such as LocalDate, ZonedDateTime and Instant.
This tutorial shows which class to use for which job, how to calculate with dates, and how to work across time zones.
1. Why Was a New Date and Time API Needed?
The old classes had well-known problems. Date is mutable, so a date shared between threads can change unexpectedly. Months in Calendar start at 0, SimpleDateFormat is not thread-safe, and there was no clean way to represent "a date without a time" or "a duration of 3 hours".
java.time, based on the experience of the Joda-Time library, fixes these problems with immutable value types and separate classes for separate concepts.
2. Choosing the Right Class
| Class | Represents | Example value |
|---|---|---|
LocalDate | a date without time or zone | 2026-11-27 |
LocalTime | a time of day | 15:30 |
LocalDateTime | date and time, no zone | 2026-11-27T15:30 |
ZonedDateTime | date and time in a zone | 2026-01-15T01:40+05:30[Asia/Kolkata] |
Instant | a point on the UTC time-line | 2026-01-14T20:10:00Z |
Period / Duration | date-based / time-based amount | P2Y8M / PT16H35M |
3. Practical Examples
Example 1: Dates, periods and formatting
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class DateTimeBasics {
public static void main(String[] args) {
LocalDate joined = LocalDate.of(2024, 2, 29); // a leap day
LocalDate today = LocalDate.of(2026, 11, 27);
// Immutable: plus/minus return new objects
System.out.println("One year later : " + joined.plusYears(1)); // adjusted to Feb 28
System.out.println("Day of week : " + today.getDayOfWeek());
Period served = Period.between(joined, today);
System.out.println("Service period : " + served.getYears() + " years, "
+ served.getMonths() + " months, " + served.getDays() + " days");
System.out.println("Days between : " + ChronoUnit.DAYS.between(joined, today));
LocalDate nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday : " + nextMonday);
LocalDateTime meeting = LocalDateTime.of(today, LocalTime.of(15, 30));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a", Locale.US);
System.out.println("Formatted : " + meeting.format(fmt));
System.out.println("Parsed : " + LocalDate.parse("2026-12-31").isAfter(today));
}
}
One year later : 2025-02-28 Day of week : FRIDAY Service period : 2 years, 8 months, 29 days Days between : 1002 Next Monday : 2026-11-30 Formatted : 27 Nov 2026, 03:30 PM Parsed : true
Adding one year to 29 February 2024 gives 28 February 2025, because the API adjusts invalid dates to the last valid day. TemporalAdjusters answers questions like "next Monday" without manual arithmetic.
Example 2: Time zones and durations
A flight departs Bengaluru and lands in New York. withZoneSameInstant converts the arrival time to New York time while keeping the same moment.
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TimeZonesAndDurations {
public static void main(String[] args) {
// A flight leaves Bengaluru at 01:40 local time
ZonedDateTime departure = ZonedDateTime.of(
LocalDateTime.of(2026, 1, 15, 1, 40), ZoneId.of("Asia/Kolkata"));
// Flight time 16 h 35 min; convert the arrival to New York time
Duration flight = Duration.ofHours(16).plusMinutes(35);
ZonedDateTime arrivalNy = departure.plus(flight).withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("Departs (IST): " + departure);
System.out.println("Arrives (NY) : " + arrivalNy);
System.out.println("Flight time : " + flight + " = " + flight.toMinutes() + " minutes");
// Instant is a point on the UTC time-line, ideal for timestamps
Instant stamp = departure.toInstant();
System.out.println("As Instant : " + stamp);
System.out.println("Epoch second : " + stamp.getEpochSecond());
}
}
Departs (IST): 2026-01-15T01:40+05:30[Asia/Kolkata] Arrives (NY) : 2026-01-15T07:45-05:00[America/New_York] Flight time : PT16H35M = 995 minutes As Instant : 2026-01-14T20:10:00Z Epoch second : 1768421400
4. How the Types Relate
5. Important Points and Best Practices
- All
java.timetypes are immutable: methods likeplusDaysreturn new objects, so always use the return value. - Store timestamps as
Instant(UTC) and convert to a zone only for display. - Use
Periodfor years, months and days andDurationfor hours, minutes and seconds. - Months are numbered 1 to 12, and
DateTimeFormatteris thread-safe, unlikeSimpleDateFormat. - For testable code, pass a
Clockinstead of callingnow()directly.
6. Summary
java.timewas added in Java 8 by JEP 150.- Use
LocalDate,LocalDateTime,ZonedDateTimeandInstantfor different needs. - All types are immutable and thread-safe.
PeriodandDurationmeasure amounts of time.- Convert between zones with
withZoneSameInstant.
Related Tutorials
- Java Date Class
- Java Calendar Class
- Java 8 Features
- Enhanced Pseudo-Random Number Generators (Java 17)
7. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between LocalDateTime and ZonedDateTime?
LocalDateTime has no time zone, so it does not identify an exact moment. ZonedDateTime adds a zone and offset, so it represents a specific instant.
Q2. What is the difference between Period and Duration?
Period is date-based (years, months, days) and Duration is time-based (hours, minutes, seconds, nanoseconds).
Q3. Why is java.time better than java.util.Date?
Its classes are immutable and thread-safe, separate concepts such as dates, times and instants, number months from 1, and include a thread-safe formatter.
Q4. How do I convert a Date to the new API?
Use date.toInstant() to get an Instant, then add a zone, for example date.toInstant().atZone(ZoneId.systemDefault()).