Sub topic 1
Why Java Needed a New Date and Time API
The Old Classes Caused Bugs
Before Java 8, programmers used java.util.Date and java.util.Calendar. These classes were easy to get wrong:
- In
Calendar, months start at 0. January is 0 and December is 11. - A
Dateis mutable. Mutable means the object can be changed after it is made. If one part of a program changes a date, every other part that shares it sees the change. - The name
Dateis misleading. ADateholds an exact moment in time, not a calendar date.
Java 8 added the java.time package to fix these problems. A package is a group of related classes.
Immutable Values: Every Change Returns a New Object
Objects in java.time are immutable. Immutable means the object can never change. A method such as plusDays does not change the date you call it on. It returns a new date, and you must store that new date in a variable.
import java.time.LocalDate;
public class Immutable {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 31);
date.plusDays(1); // result discarded, date is unchanged
System.out.println(date); // 2024-01-31
LocalDate next = date.plusDays(1);
System.out.println(next); // 2024-02-01
}
}Calendar Dates with LocalDate
LocalDate is a class for a date with no time and no time zone, such as a birthday. In java.time, months start at 1, so March is 3.
import java.time.LocalDate;
import java.time.Month;
public class Dates {
public static void main(String[] args) {
LocalDate release = LocalDate.of(2014, Month.MARCH, 18);
LocalDate later = release.plusMonths(1).plusDays(10);
System.out.println(release); // 2014-03-18
System.out.println(later); // 2014-04-28
System.out.println(later.getDayOfWeek()); // MONDAY
}
}Times of Day and LocalDateTime
LocalTime is a time of day with no date, such as 9:30. LocalDateTime is a date and a time together, still with no time zone.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class DateAndTime {
public static void main(String[] args) {
LocalTime start = LocalTime.of(9, 30);
LocalTime end = start.plusMinutes(45);
System.out.println(end); // 10:15
LocalDateTime meeting = LocalDateTime.of(LocalDate.of(2024, 7, 1), end);
System.out.println(meeting); // 2024-07-01T10:15
}
}| Type | Holds | Example |
|---|---|---|
| `LocalDate` | Date only | 2024-07-01 |
| `LocalTime` | Time only | 10:15 |
| `LocalDateTime` | Date and time | 2024-07-01T10:15 |
Exercise
What does this code print? LocalTime t = LocalTime.of(8, 0); t.plusHours(2); System.out.println(t);
Show answer
It prints 08:00. LocalTime is immutable, so plusHours returns a new object. The code never saves that object, so t stays 08:00.