← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 2 of 10

Java Date & Time

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

java
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);
	}
}

LocalDateTime

LocalDateTime combines both into a single date-and-time value, useful for representing a specific moment without needing timezone information attached.

Example: LocalDateTime

java
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);
	}
}

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

java
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));
	}
}

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

java
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);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.