Careeroza
LocalDate LocalTime and LocalDateTime
The java.time Classes
Java 8 introduced java.time, replacing the old, error-prone Date and Calendar. All classes are immutable and thread-safe; methods like plusDays return a new object.
| Class | Holds | Example value |
|---|---|---|
LocalDate | date only | 2024-08-15 |
LocalTime | time only | 09:30 |
LocalDateTime | date + time, no zone | 2024-08-15T09:30 |
ZonedDateTime | date + time + zone | 2024-08-15T09:30+05:30[Asia/Kolkata] |
Instant | a point on the UTC timeline | 2024-08-15T04:00:00Z |
Period / Duration | amount of time (days / seconds) | P1Y2M, PT2H30M |
Note: In real code you get the current date with LocalDate.now(). The examples use fixed dates so the output is always the same.
Creating and Changing Dates
Example
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class Main {
public static void main(String[] args) {
LocalDate independence = LocalDate.of(2024, Month.AUGUST, 15);
System.out.println("Date : " + independence);
System.out.println("Day of week : " + independence.getDayOfWeek());
System.out.println("Day of year : " + independence.getDayOfYear());
System.out.println("Leap year? : " + independence.isLeapYear());
LocalDate due = independence.plusDays(30).minusMonths(1).plusYears(1);
System.out.println("Changed : " + due);
System.out.println("Original : " + independence + " (unchanged, immutable)");
LocalDate firstOfMonth = independence.withDayOfMonth(1);
LocalDate lastOfMonth = independence.withDayOfMonth(independence.lengthOfMonth());
System.out.println("Month range : " + firstOfMonth + " to " + lastOfMonth);
System.out.println("Is Thursday?: " + (independence.getDayOfWeek() == DayOfWeek.THURSDAY));
LocalTime opening = LocalTime.of(9, 30);
System.out.println("Closes at : " + opening.plusHours(12).plusMinutes(15));
LocalDateTime meeting = LocalDateTime.of(2024, 8, 16, 14, 0);
System.out.println("Meeting : " + meeting);
System.out.println("Before? : " + meeting.isBefore(LocalDateTime.of(2024, 8, 16, 15, 0)));
}
}Output
Date : 2024-08-15 Day of week : THURSDAY Day of year : 228 Leap year? : true Changed : 2025-08-14 Original : 2024-08-15 (unchanged, immutable) Month range : 2024-08-01 to 2024-08-31 Is Thursday?: true Closes at : 21:45 Meeting : 2024-08-16T14:00 Before? : true