Java Dates
Dates and times in Java are values held by classes in the java.time package. A LocalDate holds a day, and a LocalDateTime holds a day with a time.
A fixed date
The of method builds a date from a year, a month, and a day. The date prints in year, month, and day order.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 1, 15);
System.out.println(date);
}
}A date and a time
LocalDateTime adds an hour and a minute to the date. The letter T separates the date from the time.
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime moment = LocalDateTime.of(2026, 1, 15, 10, 30);
System.out.println(moment);
}
}A custom date format
The pattern dd/MM/yyyy puts the day first. The format method applies the pattern to the date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 1, 15);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(date.format(formatter));
}
}Example
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 1, 15);
LocalDate later = start.plusDays(7);
System.out.println(start);
System.out.println(later);
}
}Key points
- A LocalDate value holds a date with no time of day.
- A LocalDateTime value holds a date together with a time.
- The of method builds a value from separate year, month, and day numbers.
- A DateTimeFormatter with a pattern controls how a date is printed.
- The plusDays method returns a new date a given number of days later.
- The now method returns the current date or time.
In this example, the start date is built with of from fixed numbers. The plusDays call returns a new date seven days later. The start date itself does not change. The two print lines show January 15 and January 22.
Note
Every date in this lesson is built with of, so the printed values stay the same on every run.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
Which method builds a LocalDate from a year, a month, and a day?