CKTIS / Java
Creating and shifting a local date-time
Create a local date-time with `LocalDateTime.of`, then add hours or minutes without changing the original value.
Version: Java SE 21
Syntax
import java.time.LocalDateTime;
LocalDateTime start = LocalDateTime.of(year, month, dayOfMonth, hour, minute);
LocalDateTime later = start.plusHours(hours).plusMinutes(minutes);
// Factory arguments shown: int. Amounts passed to plusHours and plusMinutes: long.java.time.LocalDateTime pairs a calendar date with a wall-clock time. It stores neither a time zone nor a UTC offset, so it does not identify an instant on its own. Its arithmetic does not account for daylight-saving transitions.
The static factory LocalDateTime.of(year, month, dayOfMonth, hour, minute) takes five int arguments in the form shown, with months numbered 1 through 12. It sets the second and nanosecond fields to zero. Other overloads let you supply seconds and optionally nanoseconds, use a Month constant instead of a month number, or combine a LocalDate and a LocalTime. In the field-based overloads, an invalid date or an out-of-range field produces a DateTimeException.
The instance methods plusHours(long hours) and plusMinutes(long minutes) add hours and minutes, respectively. A negative amount moves the value backward, and crossing midnight changes the date too. A result outside the supported date range produces a DateTimeException.
LocalDateTime is immutable: the methods return the result without changing the object you called them on. Save the returned value or use it directly in the next call, as in start.plusHours(1).plusMinutes(20).
Examples
import java.time.LocalDateTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2026, 4, 30, 22, 50);
LocalDateTime afterHours = start.plusHours(1);
LocalDateTime afterMinutes = afterHours.plusMinutes(20);
System.out.println(start);
System.out.println(afterHours);
System.out.println(afterMinutes);
System.out.println(start);
}
}Result
2026-04-30T22:50 2026-04-30T23:50 2026-05-01T00:10 2026-04-30T22:50
Adding one hour gives 23:50, and adding another 20 minutes takes the result to May 1 at 00:10. The last line repeats the original date-time. The printed form separates the date and time with `T` and omits the zero second and nanosecond fields.
Related lessons
- Java · Lesson 68 · Basic · Version: 2