The java.time package
Java 8 added an easy set of date and time classes in java.time:
| Class | Holds | Example |
|---|---|---|
LocalDate | a date | 2026-08-15 |
LocalTime | a time of day | 09:30 |
LocalDateTime | both | 2026-08-15T09:30 |
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate d = LocalDate.of(2026, 8, 15);
System.out.println(d);
System.out.println(d.getDayOfWeek());
System.out.println(d.plusDays(20));
System.out.println(d.minusMonths(1));
System.out.println(d.isLeapYear());
}
}Output
2026-08-15 SATURDAY 2026-09-04 2026-07-15 false
LocalDate.now() gives today's date. Dates can't be changed: plusDays gives you a new date, just like String methods do.
How many days between two dates?
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 10, 18);
LocalDate newYear = LocalDate.of(2027, 1, 1);
System.out.println(ChronoUnit.DAYS.between(today, newYear) + " days to go");
}
}Output
75 days to go
Formatting and reading dates
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate birthday = LocalDate.parse("25/12/2000", fmt);
System.out.println(birthday);
System.out.println(birthday.format(DateTimeFormatter.ofPattern("d MMMM yyyy")));
LocalTime t = LocalTime.of(9, 45).plusMinutes(30);
System.out.println(t);
}
}Output
2000-12-25 25 December 2000 10:15
Tip: In patterns,
MMis the month andmmis minutes. Mixing them up is a classic bug.