Java Date & Time
In this page:
LocalDate and LocalTime
LocalDate represents a calendar date with no time component, and LocalTime represents a time of day with no date — use whichever matches what you're actually modeling.
Example: LocalDate and LocalTime
import java.time.LocalDate;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 15);
LocalTime time = LocalTime.of(14, 30);
System.out.println(date);
System.out.println(time);
}
}
Login to try C/C++/Java/PHP code in the editor
LocalDateTime
LocalDateTime combines both into a single date-and-time value, useful for representing a specific moment without needing timezone information attached.
Example: LocalDateTime
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime dt = LocalDateTime.of(2024, 1, 15, 14, 30);
System.out.println(dt);
}
}
Login to try C/C++/Java/PHP code in the editor
Formatting Dates
DateTimeFormatter controls how a date or time is rendered to a string (and parsed back from one), letting you match locale-specific or application-specific formatting requirements.
Example: Formatting Dates
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 15);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(date.format(fmt));
}
}
Login to try C/C++/Java/PHP code in the editor
Modifying Dates
Because these classes are immutable, methods like plusDays() or minusMonths() return a *new* date/time object rather than modifying the original — you must capture the return value to see the change.
Example: Modifying Dates
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 1, 15);
LocalDate later = date.plusDays(10); // new object, original unchanged
System.out.println(date);
System.out.println(later);
}
}
Login to try C/C++/Java/PHP code in the editor
Duration and Period
Duration measures a span of time in seconds/nanoseconds (for time-based values), while Period measures a span in years/months/days (for date-based values) — pick based on what unit actually makes sense for your calculation.
Example: Duration and Period
import java.time.Duration;
import java.time.Period;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.ofMinutes(90);
Period period = Period.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 3, 1));
System.out.println(duration);
System.out.println(period);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: