Java Dates: Handling Time
In older versions of Java, handling dates was notoriously difficult and buggy. Since Java 8, we use the java.time API, which is much more reliable and easier to read. It provides specific classes depending on whether you need a date, a time, or both.
1. The Core Classes
| Class | Purpose | Example |
|---|---|---|
LocalDate |
Year, month, and day | 2026-04-12 |
LocalTime |
Hour, minute, second, nanosecond | 15:30:00 |
LocalDateTime |
Combines both Date and Time | 2026-04-12T15:30 |
ZonedDateTime |
Date and Time with a Time Zone | 2026-04-12T15:30+01:00[CET] |
2. Basic Usage
To get the current time, we use the .now() method.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class TimeNow {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime current = LocalDateTime.now();
System.out.println("Date: " + today);
System.out.println("Time: " + now);
}
}
3. Formatting Dates (DateTimeFormatter)
By default, Java prints dates in the ISO-8601 format (Year-Month-Day). To make it look "human-friendly," we use a formatter.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime dt = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = dt.format(myFormat);
System.out.println("Formatted: " + formattedDate); // e.g., 12-04-2026 15:38:10
4. Date Arithmetic
One of the best features is how easily you can add or subtract time without worrying about leap years or different month lengths.
LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
LocalDate lastMonth = today.minusMonths(1);
if (nextWeek.isAfter(today)) {
System.out.println("The future is bright!");
}
💻 Full Practical Example: The Deadline Tracker
Copy this to see how to calculate the difference between two dates:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Deadline {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate deadline = LocalDate.of(2026, 6, 1); // June 1st, 2026
long daysLeft = ChronoUnit.DAYS.between(today, deadline);
System.out.println("Today: " + today);
System.out.println("Project Deadline: " + deadline);
System.out.println("Days remaining: " + daysLeft);
}
}
💡 Challenge: The Birthday Countdown
- Create a
LocalDateobject for your next birthday. - Use
ChronoUnit.DAYS.between()to find out how many days are left until that date. - Print: "Only [X] days until the party!"