Java Date & Time API
java time API LocalDate LocalDateTime Instant ZonedDateTime Period Duration DateTimeFormatter java.time
Learning Objectives
After completing this lesson, you will be able to:
- Understand why the Java Date & Time API was introduced
- Learn the limitations of
DateandCalendar - Work with
LocalDate,LocalTime, andLocalDateTime - Use
ZonedDateTimeandOffsetDateTime - Format and parse dates
- Perform date and time calculations
- Work with
DurationandPeriod - Handle time zones correctly
- Use the Date & Time API in Spring Boot
- Follow enterprise best practices
- Prepare for Java interview questions
Introduction
Almost every enterprise application works with dates and times.
Examples include:
- Employee joining date
- Order creation time
- Invoice due date
- Flight schedule
- Banking transactions
- Meeting scheduler
- JWT token expiration
- Log timestamps
- Audit history
- Event scheduling
Before Java 8, developers used:
java.util.Datejava.util.Calendar
These classes had many problems:
- Mutable
- Thread Unsafe
- Confusing APIs
- Poor Time Zone Support
- Difficult Formatting
To solve these issues, Java 8 introduced the java.time API, inspired by the Joda-Time library.
It is now the standard date/time library used in:
- Spring Boot
- Hibernate
- REST APIs
- Microservices
- Banking Applications
- Cloud Applications
Why New Date API?
Old API
Date date = new Date();Calendar calendar = Calendar.getInstance();
Problems
- Mutable
- Error-prone
- Month starts from 0
- Thread unsafe
- Poor readability
New API
LocalDate today = LocalDate.now();
Benefits
- Immutable
- Thread-safe
- Easy to use
- ISO-8601 compliant
- Better Time Zone support
- Functional API
Java Time Package
java.time├── LocalDate├── LocalTime├── LocalDateTime├── ZonedDateTime├── OffsetDateTime├── Instant├── Duration├── Period├── Year├── Month├── DayOfWeek└── DateTimeFormatter
Date & Time Architecture
java.time│┌──────────────┼───────────────┐│ │ │LocalDate LocalTime LocalDateTime│ │ │└──────────────┼───────────────┘│ZonedDateTime│Instant
LocalDate
Represents only a date.
LocalDate today = LocalDate.now();System.out.println(today);
Output
2026-07-09
Creating LocalDate
LocalDate birthday =LocalDate.of(1995,5,10);System.out.println(birthday);
Output
1995-05-10
LocalTime
Represents only time.
LocalTime now =LocalTime.now();System.out.println(now);
Output
10:45:30.123
LocalDateTime
Represents both date and time.
LocalDateTime current =LocalDateTime.now();System.out.println(current);
Output
2026-07-09T10:45:30
ZonedDateTime
Represents date, time, and time zone.
ZonedDateTime india =ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));System.out.println(india);
Output
2026-07-09T10:45:30+05:30[Asia/Kolkata]
Instant
Represents a timestamp in UTC.
Instant instant =Instant.now();System.out.println(instant);
Example
2026-07-09T05:15:30Z
Commonly used for:
- Logging
- Audit Records
- Distributed Systems
- APIs
Date Calculations
Adding Days
LocalDate today =LocalDate.now();LocalDate future =today.plusDays(10);System.out.println(future);
Subtracting Months
LocalDate previous =today.minusMonths(2);
Adding Years
LocalDate retirement =today.plusYears(30);
Working with Time
LocalTime now =LocalTime.now();System.out.println(now.plusHours(2));System.out.println(now.minusMinutes(30));
Comparing Dates
LocalDate today = LocalDate.now();LocalDate tomorrow =today.plusDays(1);System.out.println(today.isBefore(tomorrow));System.out.println(today.isAfter(tomorrow));System.out.println(today.equals(tomorrow));
Period
Represents a date difference.
LocalDate joining =LocalDate.of(2020,1,1);Period period =Period.between(joining,LocalDate.now());System.out.println(period.getYears());
Output
6
Duration
Represents a time difference.
LocalTime start =LocalTime.of(9,0);LocalTime end =LocalTime.of(18,30);Duration duration =Duration.between(start,end);System.out.println(duration.toHours());
Output
9
Formatting Dates
DateTimeFormatter formatter =DateTimeFormatter.ofPattern("dd-MM-yyyy");String formatted =LocalDate.now().format(formatter);System.out.println(formatted);
Output
09-07-2026
Parsing Dates
String date ="15-08-2026";DateTimeFormatter formatter =DateTimeFormatter.ofPattern("dd-MM-yyyy");LocalDate parsed =LocalDate.parse(date,formatter);System.out.println(parsed);
Output
2026-08-15
Working with Month
Month month =LocalDate.now().getMonth();System.out.println(month);
Output
JULY
Working with DayOfWeek
DayOfWeek day =LocalDate.now().getDayOfWeek();System.out.println(day);
Output
THURSDAY
Leap Year
System.out.println(LocalDate.now().isLeapYear());
Time Zone Conversion
ZonedDateTime india =ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));ZonedDateTime london =india.withZoneSameInstant(ZoneId.of("Europe/London"));System.out.println(london);
Legacy Date Conversion
Old Date to LocalDate
Date date = new Date();LocalDate localDate =date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to Date
Date date =Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
Real-World Example: Employee Age
LocalDate birthDate =LocalDate.of(1998,5,10);int age =Period.between(birthDate,LocalDate.now()).getYears();System.out.println(age);
Real-World Example: Subscription Expiry
LocalDate expiry =LocalDate.now().plusMonths(12);System.out.println(expiry);
Real-World Example: Spring Boot Entity
@Entitypublic class Employee{private LocalDate joiningDate;private LocalDateTime createdAt;private Instant updatedAt;}
Modern Spring Boot and Hibernate support Java Time types directly.
Best Practices
Use java.time API
Avoid Date and Calendar in new applications.
Use LocalDate for Dates
Example
- Birthday
- Joining Date
Use LocalDateTime
For timestamps without a time zone.
Use Instant for Audit Logs
Provides a universal UTC timestamp.
Use ZonedDateTime
When working across multiple regions.
Use DateTimeFormatter
Avoid SimpleDateFormat in modern applications.
Store UTC in Databases
Convert to the user's local time only when displaying data.
Common Mistakes
Using Date Instead of LocalDate
Prefer
LocalDate
Ignoring Time Zones
Different users may be in different regions.
Using LocalDateTime for Global Events
Prefer
Instant
or
ZonedDateTime
Using SimpleDateFormat
Use
DateTimeFormatter
instead.
Modifying Date Objects
Java Time classes are immutable.
Every operation returns a new object.
Hands-on Exercise
Create a Java program that:
- Displays today's date.
- Displays the current time.
- Displays the current date and time.
- Calculates the age of an employee.
- Adds 30 days to the current date.
- Subtracts 6 months from today's date.
- Formats today's date as
dd-MM-yyyy. - Parses
"01-01-2027"into aLocalDate. - Converts India time to New York time.
- Creates a Spring Boot entity using
LocalDate,LocalDateTime, andInstant.
Summary
The Java Date & Time API (java.time) provides a modern, immutable, and thread-safe approach to handling dates and times. Classes such as LocalDate, LocalTime, LocalDateTime, Instant, and ZonedDateTime cover a wide range of enterprise use cases, while Period, Duration, and DateTimeFormatter simplify calculations and formatting. This API has become the standard for modern Java development and is deeply integrated with Spring Boot, Hibernate, and REST services.
Key Takeaways
java.timereplaces the legacyDateandCalendarAPIs.LocalDatestores only dates.LocalTimestores only time.LocalDateTimestores date and time without a time zone.Instantrepresents a UTC timestamp.ZonedDateTimehandles multiple time zones.Periodmeasures date differences.Durationmeasures time differences.DateTimeFormatterformats and parses dates.- The Java Time API is immutable and thread-safe.
Professional Interview Questions
1Why was the Java Date & Time API introduced?
Professional Answer
The Java Date & Time API was introduced in Java 8 to replace the older Date and Calendar classes, which were mutable, difficult to use, and not thread-safe. The new API is immutable, thread-safe, ISO-8601 compliant, and provides a cleaner, more expressive programming model for date and time operations.
Follow-up Questions
- Which package contains the new API?
- Which library inspired the Java Time API?
Interview Tip: Old API → Mutable & Complex, Java Time API → Immutable & Thread-Safe.
2What is the difference between LocalDateTime, Instant, and ZonedDateTime?
Professional Answer
LocalDateTime represents a date and time without any time zone information. Instant represents a single point on the UTC timeline and is ideal for logging and distributed systems. ZonedDateTime combines a date, time, and time zone, making it suitable for applications that operate across different geographic regions.
Follow-up Questions
- Which type is best for audit logs?
- Which type should be used for international meeting scheduling?
Interview Tip: LocalDateTime → Local Timestamp, Instant → UTC Timestamp, ZonedDateTime → Time Zone Aware.
3What is the difference between Period and Duration?
Professional Answer
Period represents a difference between two dates in terms of years, months, and days. It is designed for date-based calculations. Duration represents a difference between two times or instants in terms of hours, minutes, seconds, and nanoseconds, making it suitable for time-based calculations.
Follow-up Questions
- Can Period calculate hours?
- Can Duration calculate months?
Interview Tip: Period → Date Difference, Duration → Time Difference.