Sub topic 1
Why Java Needed a New Date and Time API
Java has shipped with date and time classes since its first release. For about 18 years, programmers used java.util.Date and java.util.Calendar. Those classes caused so many bugs that Java 8 added a new package, java.time, to replace them.
This chapter explains what went wrong with the old classes. You need to know this for two reasons. First, you will still see Date and Calendar in older code and libraries. Second, the design of java.time makes more sense once you know which problems it was built to fix.
A Short History
An API (Application Programming Interface) is a set of classes and methods that a library gives you to use. Java's date and time API changed in three main steps.
A deprecated method is one that still works but is marked "do not use". The compiler warns you when you call it. Date had most of its methods deprecated only one year after it came out, which shows how quickly its problems appeared.
Joda-Time was a free library that many programmers used in place of the built-in classes. Its author, Stephen Colebourne, then led JSR 310, the official proposal that became java.time. A JSR (Java Specification Request) is a formal proposal to add something to the Java platform.
Problem 1: The Names Are Misleading
The name java.util.Date suggests a calendar date, like "15 February 2024". A Date object does not hold a date. It holds a single number: the milliseconds since 1 January 1970 at midnight UTC. UTC (Coordinated Universal Time) is the world's reference time, with no time zone shift applied.
So a Date is really a point on the timeline. It has no year, month, or day of its own. When you print it, Java converts that number into your computer's default time zone. The same Date object prints different text on a computer in London than on one in Tokyo.
java.sql.Date makes this worse. It extends java.util.Date, which means it inherits everything Date has, but it is supposed to mean "a date with no time". Two classes with the same short name mean different things, and one pretends to be the other.
Problem 2: Strange Numbering
The old classes count years and months in surprising ways:
- The
Dateconstructor treats the year as "years since 1900". Passing2024means the year 3924. - Months start at 0. January is 0 and December is 11.
- Days of the month start at 1, as you would expect.
The mix of rules makes mistakes easy. Run this program to see them:
import java.util.Calendar;
import java.util.Date;
public class LegacyNumbering {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// The programmer wants 15 February 2024.
Date d = new Date(2024, 2, 15);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
System.out.println(cal.get(Calendar.YEAR)); // 3924
System.out.println(cal.get(Calendar.MONTH)); // 2, which means March
System.out.println(cal.get(Calendar.DAY_OF_MONTH)); // 15
}
}The programmer typed 2024, 2, 15 and got 15 March 3924. Nothing failed and no error appeared. The wrong date just went on into the rest of the program.
Problem 3: Silent Rollover
Calendar is lenient by default. A lenient object accepts impossible values and quietly turns them into something valid. Month 12 does not exist, because months run from 0 to 11, so Calendar rolls it over into January of the next year:
import java.util.Calendar;
public class LegacyLenient {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2024, 12, 1); // the programmer means December
System.out.println(cal.get(Calendar.YEAR)); // 2025
System.out.println(cal.get(Calendar.MONTH)); // 0, which means January
}
}A bug like this can stay hidden for months. It only shows up when someone notices a report dated a year too late.
Problem 4: Objects That Change Under You
A mutable object is one whose contents can change after it is created. Date and Calendar are both mutable. When two variables point to the same Date, a change made through one variable is seen through the other:
import java.util.Date;
public class LegacyMutable {
public static void main(String[] args) {
Date start = new Date(0); // 1970-01-01T00:00:00Z
Date deadline = start; // same object, not a copy
deadline.setTime(86_400_000L); // move "deadline" forward one day
System.out.println(start.getTime()); // 86400000, start moved too
}
}This gets dangerous when a class stores a Date that a caller passed in. The caller can change it later, and the class's data changes without the class doing anything. To protect themselves, careful programmers made copies of every Date going in and coming out. That kind of copy is called a defensive copy.
Problem 5: Not Safe Across Threads
A thread is one path of work running inside a program. Many programs, such as web servers, run many threads at the same time. SimpleDateFormat, the old class for turning dates into text, keeps working data inside itself while it formats. If two threads share one SimpleDateFormat, they overwrite each other's data. The result can be wrong dates or random exceptions. These failures happen only under load, so they are hard to reproduce.
Problem 6: Missing Concepts
The old API had one main type for everything. It had no proper way to say:
- "A date with no time", like a birthday.
- "A time with no date", like "the shop opens at 09:00".
- "An amount of time", like "3 days" or "90 minutes".
- "A named time zone with its daylight saving rules", kept together with the date and time.
Programmers had to fake these with a full Date and a set of rules that only they knew about. For example, they might decide that "midnight means no time". Those hidden rules broke when code crossed time zones.
How java.time Fixes These Problems
The table maps each problem to the fix in java.time. Later chapters cover each type in detail.
| Legacy problem | java.time answer |
|---|---|
| `Date` name hides that it is an instant | Separate types: `Instant` for a moment, `LocalDate` for a calendar date |
| Year offset of 1900, months from 0 | Real years, months numbered 1 to 12, and a `Month` enum |
| Invalid values silently roll over | Invalid values throw `DateTimeException` |
| Mutable objects | Every type is immutable; changes return a new object |
| `SimpleDateFormat` not thread-safe | `DateTimeFormatter` is immutable and safe to share |
| No types for dates, times, or amounts | `LocalDate`, `LocalTime`, `Duration`, `Period`, and more |
Here is the same intent as the numbering example, written with java.time:
import java.time.DateTimeException;
import java.time.LocalDate;
public class ModernPreview {
public static void main(String[] args) {
LocalDate d = LocalDate.of(2024, 2, 15);
System.out.println(d); // 2024-02-15
try {
LocalDate.of(2024, 13, 1);
} catch (DateTimeException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}The date prints as the programmer meant it, in the standard ISO 8601 format (year-month-day). The impossible month 13 is rejected right away instead of turning into a wrong date.
Exercises
Exercise
A legacy program calls new Date(99, 0, 1) with deprecated constructor arguments. Which calendar date does it represent?
Show answer
1 January 1999. The year is counted from 1900, so 99 means 1999, and month 0 means January.
Exercise
Why can a class that stores a java.util.Date passed in by a caller end up with changed data, even though the class never modifies it?
Show answer
Date is mutable. The class and the caller hold references to the same object, so if the caller later calls a method such as setTime on it, the stored value changes too. The fix in legacy code is a defensive copy. In java.time the problem cannot happen because the objects are immutable.
Exercise
With a lenient Calendar, what does cal.set(2023, 1, 30) produce, given that 2023 is not a leap year?
Show answer
2 March 2023. Month 1 is February, which has 28 days in 2023, so day 30 rolls over two days into March. LocalDate.of(2023, 2, 30) would throw a DateTimeException instead.