LocalTime and LocalDateTime
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A LocalTime is a time on a clock, such as 10:30, with no date. A LocalDateTime joins a date and a time into one value, such as 15 March 2024 at 10:30.
LocalTime: a clock time for slots
Many values repeat every day at the same clock time: the first class at 09:00, the library opening at 08:30, the exam slot from 10:00 to 13:00. These are clock times with no date, so LocalTime fits them.
Example 1 · Class periods with LocalTime
import java.time.LocalTime;
public class TimetableDemo { public static void main(String[] args) { LocalTime start = LocalTime.of(9, 0); int periodMinutes = 50;
for (int p = 1; p <= 4; p++) { LocalTime end = start.plusMinutes(periodMinutes); System.out.println("Period " + p + ": " + start + " to " + end); start = end.plusMinutes(10); // 10-minute break }
LocalTime lab = LocalTime.parse("14:30"); System.out.println("Lab starts at hour " + lab.getHour() + ", minute " + lab.getMinute()); System.out.println("Noon is " + LocalTime.NOON); }}Period 1: 09:00 to 09:50 Period 2: 10:00 to 10:50 Period 3: 11:00 to 11:50 Period 4: 12:00 to 12:50 Lab starts at hour 14, minute 30 Noon is 12:00
What this code does
plusMinutesreturns a newLocalTime, so the loop stores each result inendand then movesstartforward. Times print in 24-hour form and hide zero seconds.LocalTime.parse("14:30")reads ISO textHH:mm.getHour()gives 14, not 2: there is no AM or PM inside aLocalTime.
Create one with LocalTime.of(10, 30), LocalTime.of(14, 30, 15) with seconds, or LocalTime.parse("09:30"). Hours use the 24-hour clock, 0 to 23, so 2:30 in the afternoon is 14:30. LocalTime.NOON and LocalTime.MIDNIGHT are ready-made constants. Read the parts with getHour(), getMinute(), getSecond() and getNano(). A nanosecond is one billionth of a second; LocalTime can store that much detail.
LocalTime.of(10, 30) prints 10:30, but LocalTime.of(10, 30, 15) prints 10:30:15.Adding time, and the wrap at midnight
plusHours, plusMinutes and plusSeconds return a new time, just like plusDays on a date. The old time never changes.
Example 2 · LocalTime wraps at midnight
import java.time.LocalDateTime;import java.time.LocalTime;
public class MidnightWrapDemo { public static void main(String[] args) { LocalTime late = LocalTime.of(23, 30); System.out.println("23:30 + 45 min (LocalTime): " + late.plusMinutes(45));
LocalDateTime lateOnDay = LocalDateTime.of(2024, 3, 15, 23, 30); System.out.println("23:30 + 45 min (LocalDateTime): " + lateOnDay.plusMinutes(45));
System.out.println("00:10 - 20 min (LocalTime): " + LocalTime.of(0, 10).minusMinutes(20)); }}23:30 + 45 min (LocalTime): 00:15 23:30 + 45 min (LocalDateTime): 2024-03-16T00:15 00:10 - 20 min (LocalTime): 23:50
What this code does
- A
LocalTimehas no date, so 23:30 plus 45 minutes wraps to 00:15 and the passing of a day is lost. Going back past midnight wraps the other way, to 23:50. - The same addition on a
LocalDateTimemoves to 16 March. UseLocalDateTimewhenever a time can cross midnight and the day matters.
A LocalTime has no date, so it wraps round the clock face. 23:30 plus 45 minutes is 00:15, and nothing tells you that a day has passed. That is fine for "what time will the clock show?", but wrong for "when does the overnight train arrive?".
Trace the code
Trace a time that wraps past midnight
Variables
- start
- 22:30
Output
(nothing printed yet)Line 5LocalTime.of(22, 30) builds the clock time 22:30. A LocalTime has no date.
LocalDateTime: a date with a time
When the day matters, use LocalDateTime. A train leaves on 15 March 2024 at 22:30. An exam starts on 1 April 2024 at 10:00.
Example 3 · An overnight train with LocalDateTime
import java.time.LocalDateTime;
public class TrainJourneyDemo { public static void main(String[] args) { LocalDateTime departs = LocalDateTime.parse("2024-03-15T22:30"); LocalDateTime arrives = departs.plusHours(9).plusMinutes(45);
System.out.println("Departs: " + departs); System.out.println("Arrives: " + arrives); System.out.println("Arrival date: " + arrives.toLocalDate()); System.out.println("Arrival time: " + arrives.toLocalTime()); System.out.println("Arrival day: " + arrives.getDayOfWeek()); }}Departs: 2024-03-15T22:30 Arrives: 2024-03-16T08:15 Arrival date: 2024-03-16 Arrival time: 08:15 Arrival day: SATURDAY
What this code does
- ISO date-time text has a
Tbetween the date and the time. Printing aLocalDateTimeuses the same form,2024-03-16T08:15. plusHours(9).plusMinutes(45)chains two changes; each call returns a new value.toLocalDate()andtoLocalTime()split the result for a ticket that shows them separately.
Create one with LocalDateTime.of(2024, 3, 15, 22, 30) or parse ISO text with a T between the date and the time: LocalDateTime.parse("2024-03-15T22:30").
Adding time now moves the date as needed: 22:30 on 15 March plus 9 hours is 07:30 on 16 March. toLocalDate() and toLocalTime() split it back into its two parts.
Like LocalDate, it is "local": it has no time zone. It means "this date and clock time" for whoever reads it. Zones come in a later lesson.
Combining a date and a time
Apps often store the date and the time slot separately. An exam timetable has many dates but the same 10:00 slot. Joining them gives a LocalDateTime.
Example 4 · Exam timetable: combining dates and a slot
import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;
public class ExamSlotDemo { public static void main(String[] args) { LocalTime morningSlot = LocalTime.of(10, 0); LocalDate maths = LocalDate.of(2024, 4, 1); LocalDate physics = LocalDate.of(2024, 4, 3); LocalDate chemistry = LocalDate.of(2024, 4, 5);
LocalDateTime a = maths.atTime(morningSlot); LocalDateTime b = morningSlot.atDate(physics); LocalDateTime c = LocalDateTime.of(chemistry, morningSlot); LocalDateTime d = chemistry.atTime(14, 0);
System.out.println("Maths: " + a); System.out.println("Physics: " + b); System.out.println("Chemistry: " + c); System.out.println("Practical: " + d); System.out.println("Gates open: " + maths.atStartOfDay()); }}Maths: 2024-04-01T10:00 Physics: 2024-04-03T10:00 Chemistry: 2024-04-05T10:00 Practical: 2024-04-05T14:00 Gates open: 2024-04-01T00:00
What this code does
atTime,atDateandLocalDateTime.of(date, time)all build the same kind of value; pick the one that reads best.atTime(14, 0)takes the hour and minute directly.atStartOfDay()gives 00:00 on that date. Keeping the slot as oneLocalTimemeans a change to 09:30 is made in one place.
date.atTime(10, 0)ordate.atTime(slot): start from the date and add a time.slot.atDate(date): start from the time and add a date. Same result.LocalDateTime.of(date, slot): the factory method form.date.atStartOfDay(): the date at 00:00, the very start of that day.
truncatedTo: drop seconds and nanoseconds
A punch-in machine may record 09:14:37.123456789. A report wants just 09:14. truncatedTo(ChronoUnit.MINUTES) sets every smaller part to zero and returns a new time. Truncate means cut off; it never rounds, so 09:14:59 also becomes 09:14.
Example 5 · truncatedTo for punch-in times
import java.time.LocalDateTime;import java.time.LocalTime;import java.time.temporal.ChronoUnit;
public class PunchInDemo { public static void main(String[] args) { LocalTime punch = LocalTime.of(9, 14, 37, 123_456_789); System.out.println("Raw: " + punch); System.out.println("Seconds: " + punch.truncatedTo(ChronoUnit.SECONDS)); System.out.println("Minutes: " + punch.truncatedTo(ChronoUnit.MINUTES)); System.out.println("Hours: " + punch.truncatedTo(ChronoUnit.HOURS));
LocalTime late = LocalTime.of(9, 14, 59); System.out.println("09:14:59 to minutes: " + late.truncatedTo(ChronoUnit.MINUTES));
LocalDateTime login = LocalDateTime.of(2024, 3, 15, 18, 45, 10); System.out.println("Day of login: " + login.truncatedTo(ChronoUnit.DAYS)); }}Raw: 09:14:37.123456789 Seconds: 09:14:37 Minutes: 09:14 Hours: 09:00 09:14:59 to minutes: 09:14 Day of login: 2024-03-15T00:00
What this code does
- The fourth number in
LocalTime.ofis nanoseconds, and printing shows them all.truncatedTocuts off every part smaller than the unit you pass. - It never rounds: 09:14:59 becomes 09:14, not 09:15. On a
LocalDateTime, truncating toDAYSgives midnight of the same date.
ChronoUnit is an enum of time units in java.time.temporal: SECONDS, MINUTES, HOURS, DAYS and more. On a LocalDateTime, truncatedTo(ChronoUnit.DAYS) gives midnight of that day.
Example 6 · Invalid times fail fast
import java.time.DateTimeException;import java.time.LocalTime;
public class BadTimeDemo { public static void main(String[] args) { try { System.out.println(LocalTime.of(24, 0)); } catch (DateTimeException e) { System.out.println("of failed: " + e.getMessage()); }
try { System.out.println(LocalTime.parse("9:30")); } catch (DateTimeException e) { System.out.println("parse failed: " + e.getMessage()); }
System.out.println("Last minute of the day: " + LocalTime.of(23, 59)); }}of failed: Invalid value for HourOfDay (valid values 0 - 23): 24 parse failed: Text '9:30' could not be parsed at index 0 Last minute of the day: 23:59
What this code does
- Hours run from 0 to 23, so 24 is rejected with a message that names the valid range. Midnight is written
LocalTime.of(0, 0)orLocalTime.MIDNIGHT. - ISO time text needs two digits for the hour, so
"9:30"fails and"09:30"works. Reading other styles needs a formatter, covered later.
Next step
Check your understanding
11 quick questions