Skip to content
C

Date and Time API

Java's modern Date and Time API (introduced in Java 8, mainly in the java.time package) provides clear, reliable classes like LocalDate, LocalTime, and LocalDateTime for handling dates and times.


1. What is the Date and Time API?

Java's modern Date and Time API (introduced in Java 8, mainly in the java.time package) provides clear, reliable classes like LocalDate, LocalTime, and LocalDateTime for handling dates and times.

2. Why is it used?

Handling dates and times correctly (accounting for time zones, formatting, and calculations) is genuinely tricky. This API provides a cleaner, more reliable way to do it, replacing older, more error-prone approaches.

3. Real-Life Example

Think of a well-designed calendar app that can clearly tell you today's date, add or subtract days accurately, and never gets confused about how many days are in February during a leap year. This API is built to handle that same kind of reliable date logic.

4. Syntax

java
LocalDate today = LocalDate.now(); LocalDate futureDate = today.plusDays(10);

5. Example Program

java
import java.time.LocalDate; public class DateTimeDemo { public static void main(String[] args) { LocalDate today = LocalDate.now(); LocalDate nextWeek = today.plusDays(7); System.out.println("Today: " + today); System.out.println("Next week: " + nextWeek); } }

Output:

Today: 2026-09-01
Next week: 2026-09-08

(Exact dates will vary depending on when the program is run.)

6. Key Points to Remember

  • LocalDate handles only dates; LocalTime handles only times; LocalDateTime handles both together.
  • Objects from this API are immutable — methods like plusDays() return a new object rather than changing the original.
  • This modern API is preferred over the older Date and Calendar classes for new Java code.