← Back to Chapters

LocalDate & LocalTime

? LocalDate & ⏰ LocalTime

? Quick Overview

LocalDate and LocalTime are part of the Java 8 java.time API. They represent date and time independently, without timezone information. These classes are immutable, thread-safe, and far superior to the old Date and Calendar.

? Key Concepts

  • LocalDate → Date only (year, month, day)
  • LocalTime → Time only (hour, minute, second)
  • No timezone or offset involved
  • Immutable and thread-safe
  • Located in java.time package

? Interactive Java Lab

Click the buttons to simulate Java method calls and see the result instantly.

LocalDate Object
Loading...
LocalTime Object
Loading...

? Syntax & Theory

These classes are created using static factory methods instead of constructors. Common methods include now(), of(), plusDays(), minusHours(), and getDayOfWeek().

? View Code Example
// Importing LocalDate and LocalTime classes
import java.time.LocalDate;
import java.time.LocalTime;

public class LocalDateLocalTimeDemo {
public static void main(String[] args) {

// Getting current date
LocalDate today = LocalDate.now();

// Getting current time
LocalTime now = LocalTime.now();

System.out.println("Date: " + today);
System.out.println("Time: " + now);
}
}

? Live Output / Explanation

The program fetches the system’s current date and time. Output will vary based on when the program is executed.

Sample Output:

Date: 2025-12-18
Time: 13:05:42.123

? More Practical Usage

? View Code Example
// Demonstrating date and time manipulation
LocalDate examDate = LocalDate.of(2025, 3, 10);
LocalTime examTime = LocalTime.of(10, 30);

// Adding days and hours
LocalDate newDate = examDate.plusDays(5);
LocalTime newTime = examTime.plusHours(2);

System.out.println(newDate);
System.out.println(newTime);

✅ Tips & Best Practices

  • Prefer java.time API over legacy date classes
  • Use LocalDate when time is irrelevant
  • Use LocalTime for scheduling or time-only logic
  • Combine with LocalDateTime when needed

? Try It Yourself

  1. Create a program to print your birthday using LocalDate
  2. Add 7 days to today’s date and display the result
  3. Display the current hour and minute using LocalTime
  4. Check what day of the week a specific date falls on