← Back to Chapters

Java Date & Time API

⏰ Java Date & Time API (java.time)

? Quick Overview

The Java Date and Time API (java.time) was introduced in Java 8 to fix the problems of older classes like Date and Calendar. It is immutable, thread-safe, and much easier to understand and use.

? Key Concepts

  • LocalDate — date without time
  • LocalTime — time without date
  • LocalDateTime — date and time
  • ZonedDateTime — date and time with timezone
  • Period & Duration — date/time differences

? Syntax / Theory

All modern date and time classes are available inside the java.time package. These classes are immutable, meaning once created, their values cannot be changed. Any modification returns a new object.

? Code Examples

? View Code Example
// Creating and displaying current date
import java.time.LocalDate;

public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today);
}
}
? View Code Example
// Working with date and time together
import java.time.LocalDateTime;

public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
}
}

? Live Output / Explanation

Sample Output

2025-12-18
2025-12-18T12:30:45.123

The output depends on the current system date and time. The T separates date and time as per ISO-8601 standard.

⚡ Interactive Playground: Java Time Machine

See how Java methods manipulate time in real-time.

LocalTime.now()
--:--:--

Updates every second (nanoseconds hidden)

LocalDate date = ...
Wait...

Click buttons to modify the date object

✅ Tips & Best Practices

  • Always prefer java.time over legacy Date and Calendar
  • Use LocalDate for birthdays and holidays
  • Use ZonedDateTime for global applications
  • Keep date-time objects immutable

? Try It Yourself

  • Create a program to add 10 days to the current date
  • Find the difference between two dates using Period
  • Display current time in a different timezone