Java Tutorial 0/145 lessons ~6 min read Lesson 33

    Java Date & Time API

    java time API LocalDate LocalDateTime Instant ZonedDateTime Period Duration DateTimeFormatter java.time

    Course progress0%
    Focus
    33 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    After completing this lesson, you will be able to:

    • Understand why the Java Date & Time API was introduced
    • Learn the limitations of Date and Calendar
    • Work with LocalDate, LocalTime, and LocalDateTime
    • Use ZonedDateTime and OffsetDateTime
    • Format and parse dates
    • Perform date and time calculations
    • Work with Duration and Period
    • 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.Date
    • java.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

    code
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();

    Problems

    • Mutable
    • Error-prone
    • Month starts from 0
    • Thread unsafe
    • Poor readability

    New API

    code
    LocalDate today = LocalDate.now();

    Benefits

    • Immutable
    • Thread-safe
    • Easy to use
    • ISO-8601 compliant
    • Better Time Zone support
    • Functional API

    Java Time Package

    code
    java.time
    ├── LocalDate
    ├── LocalTime
    ├── LocalDateTime
    ├── ZonedDateTime
    ├── OffsetDateTime
    ├── Instant
    ├── Duration
    ├── Period
    ├── Year
    ├── Month
    ├── DayOfWeek
    └── DateTimeFormatter

    Date & Time Architecture

    code
    java.time
    ┌──────────────┼───────────────┐
    │ │ │
    LocalDate LocalTime LocalDateTime
    │ │ │
    └──────────────┼───────────────┘
    ZonedDateTime
    Instant

    LocalDate

    Represents only a date.

    code
    LocalDate today = LocalDate.now();
    System.out.println(today);

    Output

    code
    2026-07-09

    Creating LocalDate

    code
    LocalDate birthday =
    LocalDate.of(
    1995,
    5,
    10
    );
    System.out.println(birthday);

    Output

    code
    1995-05-10

    LocalTime

    Represents only time.

    code
    LocalTime now =
    LocalTime.now();
    System.out.println(now);

    Output

    code
    10:45:30.123

    LocalDateTime

    Represents both date and time.

    code
    LocalDateTime current =
    LocalDateTime.now();
    System.out.println(current);

    Output

    code
    2026-07-09T10:45:30

    ZonedDateTime

    Represents date, time, and time zone.

    code
    ZonedDateTime india =
    ZonedDateTime.now(
    ZoneId.of("Asia/Kolkata")
    );
    System.out.println(india);

    Output

    code
    2026-07-09T10:45:30+05:30[Asia/Kolkata]

    Instant

    Represents a timestamp in UTC.

    code
    Instant instant =
    Instant.now();
    System.out.println(instant);

    Example

    code
    2026-07-09T05:15:30Z

    Commonly used for:

    • Logging
    • Audit Records
    • Distributed Systems
    • APIs

    Date Calculations

    Adding Days

    code
    LocalDate today =
    LocalDate.now();
    LocalDate future =
    today.plusDays(10);
    System.out.println(future);

    Subtracting Months

    code
    LocalDate previous =
    today.minusMonths(2);

    Adding Years

    code
    LocalDate retirement =
    today.plusYears(30);

    Working with Time

    code
    LocalTime now =
    LocalTime.now();
    System.out.println(
    now.plusHours(2)
    );
    System.out.println(
    now.minusMinutes(30)
    );

    Comparing Dates

    code
    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.

    code
    LocalDate joining =
    LocalDate.of(
    2020,
    1,
    1
    );
    Period period =
    Period.between(
    joining,
    LocalDate.now()
    );
    System.out.println(
    period.getYears()
    );

    Output

    code
    6

    Duration

    Represents a time difference.

    code
    LocalTime start =
    LocalTime.of(
    9,
    0
    );
    LocalTime end =
    LocalTime.of(
    18,
    30
    );
    Duration duration =
    Duration.between(
    start,
    end
    );
    System.out.println(
    duration.toHours()
    );

    Output

    code
    9

    Formatting Dates

    code
    DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern(
    "dd-MM-yyyy"
    );
    String formatted =
    LocalDate.now()
    .format(formatter);
    System.out.println(formatted);

    Output

    code
    09-07-2026

    Parsing Dates

    code
    String date =
    "15-08-2026";
    DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern(
    "dd-MM-yyyy"
    );
    LocalDate parsed =
    LocalDate.parse(
    date,
    formatter
    );
    System.out.println(parsed);

    Output

    code
    2026-08-15

    Working with Month

    code
    Month month =
    LocalDate.now()
    .getMonth();
    System.out.println(month);

    Output

    code
    JULY

    Working with DayOfWeek

    code
    DayOfWeek day =
    LocalDate.now()
    .getDayOfWeek();
    System.out.println(day);

    Output

    code
    THURSDAY

    Leap Year

    code
    System.out.println(
    LocalDate.now()
    .isLeapYear()
    );

    Time Zone Conversion

    code
    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

    code
    Date date = new Date();
    LocalDate localDate =
    date.toInstant()
    .atZone(
    ZoneId.systemDefault()
    )
    .toLocalDate();

    LocalDate to Date

    code
    Date date =
    Date.from(
    localDate
    .atStartOfDay(
    ZoneId.systemDefault()
    )
    .toInstant()
    );

    Real-World Example: Employee Age

    code
    LocalDate birthDate =
    LocalDate.of(
    1998,
    5,
    10
    );
    int age =
    Period.between(
    birthDate,
    LocalDate.now()
    ).getYears();
    System.out.println(age);

    Real-World Example: Subscription Expiry

    code
    LocalDate expiry =
    LocalDate.now()
    .plusMonths(12);
    System.out.println(expiry);

    Real-World Example: Spring Boot Entity

    code
    @Entity
    public 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

    code
    LocalDate

    Ignoring Time Zones

    Different users may be in different regions.

    Using LocalDateTime for Global Events

    Prefer

    code
    Instant

    or

    code
    ZonedDateTime

    Using SimpleDateFormat

    Use

    code
    DateTimeFormatter

    instead.

    Modifying Date Objects

    Java Time classes are immutable.

    Every operation returns a new object.

    Hands-on Exercise

    Create a Java program that:

    1. Displays today's date.
    2. Displays the current time.
    3. Displays the current date and time.
    4. Calculates the age of an employee.
    5. Adds 30 days to the current date.
    6. Subtracts 6 months from today's date.
    7. Formats today's date as dd-MM-yyyy.
    8. Parses "01-01-2027" into a LocalDate.
    9. Converts India time to New York time.
    10. Creates a Spring Boot entity using LocalDate, LocalDateTime, and Instant.

    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.time replaces the legacy Date and Calendar APIs.
    • LocalDate stores only dates.
    • LocalTime stores only time.
    • LocalDateTime stores date and time without a time zone.
    • Instant represents a UTC timestamp.
    • ZonedDateTime handles multiple time zones.
    • Period measures date differences.
    • Duration measures time differences.
    • DateTimeFormatter formats 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.

    Ready to mark this lesson complete?Track your journey across the entire course.