Sub topic 4
Times of Day with LocalTime
A LocalTime is a time of day with no date and no time zone. It holds an hour, a minute, a second, and a fraction of a second. "7:15 in the morning" and "half past six in the evening" are good examples of times it can hold.
This chapter shows you how to create a LocalTime, read its parts, change it, and compare two times. You will also see the edge cases that catch beginners, such as times that roll past midnight.
Why a Time Without a Date Is Useful
Many real rules only care about the clock and not the calendar. Here are some examples:
- A shop opens at 09:00 and closes at 17:30 every day.
- An alarm rings at 07:15.
- A daily backup job starts at 02:00.
None of these rules names a day. If you stored them with a full date, you would have to pick a fake date, and that date could cause bugs later. LocalTime holds only the part you need.
Like every java.time type, LocalTime is immutable. An immutable object is one that never changes after it is created. Each method that seems to "change" a time actually returns a new LocalTime.
Creating a LocalTime
You can build a time in several ways.
import java.time.LocalTime;
public class CreateTimes {
public static void main(String[] args) {
LocalTime alarm = LocalTime.of(7, 15); // hour, minute
LocalTime lunch = LocalTime.of(12, 30, 45); // hour, minute, second
LocalTime train = LocalTime.parse("18:05"); // from text
System.out.println(alarm); // 07:15
System.out.println(lunch); // 12:30:45
System.out.println(train); // 18:05
System.out.println(LocalTime.NOON); // 12:00
System.out.println(LocalTime.MIDNIGHT); // 00:00
System.out.println(LocalTime.MAX); // 23:59:59.999999999
}
}Some points to notice:
LocalTime.ofis a static factory method. A factory method is a method that builds and returns a new object, and you call it instead ofnew.- Hours use the 24-hour clock, so 6 p.m. is
18. - When printed, a time leaves out its seconds if they are zero. That is why
alarmprints as07:15and not07:15:00. LocalTime.parsereads text in the standardHH:mmorHH:mm:ssform. A later chapter covers custom text formats.
You can also get the current time with LocalTime.now(). It reads your computer's clock and time zone, so the result changes every time you run the program.
Reading the Parts of a Time
Getter methods let you pull out each part of a time.
import java.time.LocalTime;
public class ReadTimes {
public static void main(String[] args) {
LocalTime t = LocalTime.of(14, 5, 30);
System.out.println(t.getHour()); // 14
System.out.println(t.getMinute()); // 5
System.out.println(t.getSecond()); // 30
System.out.println(t.getNano()); // 0
System.out.println(t.toSecondOfDay()); // 50730
}
}toSecondOfDay() counts the seconds since midnight: 14 × 3600 + 5 × 60 + 30 = 50730. The reverse method, LocalTime.ofSecondOfDay(50730), gives back 14:05:30.
Changing a Time
Methods that start with plus, minus, and with return a new time.
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class ChangeTimes {
public static void main(String[] args) {
LocalTime start = LocalTime.of(10, 30);
System.out.println(start.plusMinutes(45)); // 11:15
System.out.println(start.minusHours(3)); // 07:30
System.out.println(start.withHour(8)); // 08:30
LocalTime precise = LocalTime.of(10, 30, 59);
System.out.println(precise.truncatedTo(ChronoUnit.HOURS)); // 10:00
System.out.println(precise.truncatedTo(ChronoUnit.MINUTES)); // 10:30
System.out.println(start); // 10:30, the original is unchanged
}
}| Method | What it does | Example result from 10:30 |
|---|---|---|
| `plusHours(n)`, `plusMinutes(n)`, `plusSeconds(n)` | Moves the time forward | `plusMinutes(45)` gives 11:15 |
| `minusHours(n)`, `minusMinutes(n)`, `minusSeconds(n)` | Moves the time back | `minusHours(3)` gives 07:30 |
| `withHour(h)`, `withMinute(m)`, `withSecond(s)` | Replaces one part | `withHour(8)` gives 08:30 |
| `truncatedTo(unit)` | Drops every part smaller than the unit | `truncatedTo(HOURS)` gives 10:00 |
Edge Case: Times Wrap Around Midnight
A LocalTime has no date, so it cannot move into "tomorrow". When you go past midnight, the time wraps around like the hands of a clock.
import java.time.LocalTime;
public class WrapAround {
public static void main(String[] args) {
System.out.println(LocalTime.of(23, 0).plusHours(2)); // 01:00
System.out.println(LocalTime.of(0, 30).minusMinutes(45)); // 23:45
System.out.println(LocalTime.MAX.plusNanos(1)); // 00:00
System.out.println(LocalTime.of(9, 0).plusHours(24)); // 09:00
}
}No error happens and no warning is shown. The program silently loses track of the extra day. If your code needs to know that a day has passed, for example a night shift that ends the next morning, use LocalDateTime instead. The next chapter covers it.
Comparing Two Times
LocalTime gives you clear comparison methods.
a.isBefore(b)is true ifacomes earlier in the day thanb.a.isAfter(b)is true ifacomes later in the day thanb.a.equals(b)is true if both times are exactly the same.a.compareTo(b)returns a negative number, zero, or a positive number. Sorting uses this method.
The example below checks whether a shop is open. It also handles a shop that stays open overnight. In that case the closing time is earlier on the clock than the opening time.
import java.time.LocalTime;
public class OpeningHours {
static boolean isOpen(LocalTime open, LocalTime close, LocalTime now) {
if (open.isBefore(close)) {
// Normal day: open <= now < close
return !now.isBefore(open) && now.isBefore(close);
}
// Overnight: open late, close the next morning
return !now.isBefore(open) || now.isBefore(close);
}
public static void main(String[] args) {
LocalTime nine = LocalTime.of(9, 0);
LocalTime halfFive = LocalTime.of(17, 30);
System.out.println(isOpen(nine, halfFive, LocalTime.of(12, 15))); // true
System.out.println(isOpen(nine, halfFive, LocalTime.of(17, 30))); // false
System.out.println(isOpen(nine, halfFive, LocalTime.of(9, 0))); // true
LocalTime ten = LocalTime.of(22, 0);
LocalTime six = LocalTime.of(6, 0);
System.out.println(isOpen(ten, six, LocalTime.of(23, 30))); // true
System.out.println(isOpen(ten, six, LocalTime.of(3, 0))); // true
System.out.println(isOpen(ten, six, LocalTime.of(12, 0))); // false
}
}!now.isBefore(open) means "now is at or after opening time". The shop is open at exactly 09:00 and closed at exactly 17:30. Using one inclusive end and one exclusive end is a common choice, and it stops two time ranges from overlapping at their edges.
Edge Case: Invalid Values
Java checks every value you pass. A value outside the allowed range throws an exception. An exception is an error object that stops the normal flow of the program.
import java.time.DateTimeException;
import java.time.LocalTime;
public class InvalidTimes {
public static void main(String[] args) {
try {
LocalTime.of(25, 0);
} catch (DateTimeException e) {
System.out.println("Error: " + e.getMessage());
}
try {
LocalTime.parse("24:00");
} catch (DateTimeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Both calls fail. Hours run from 0 to 23, minutes and seconds from 0 to 59, and nanoseconds from 0 to 999,999,999. The text 24:00 is rejected because the end of the day is written as 00:00 or represented by LocalTime.MAX. If the time comes from user input, catch DateTimeException (DateTimeParseException is a subclass) and show a helpful message.
Common Mistakes
- Forgetting to store the result. Changing methods return a new object and leave the original as it was.
- Using LocalTime for events that cross midnight. The day is lost when the time wraps. Use
LocalDateTimeinstead. - Using LocalTime for a moment shared worldwide. "09:00" means a different moment in Tokyo and in London. Time zones are covered in later chapters.
- Writing 12-hour values.
LocalTime.of(6, 0)is 6 a.m. For 6 p.m., writeLocalTime.of(18, 0).
Exercise
What does this code print? LocalTime t = LocalTime.of(22, 40); t.plusMinutes(30); System.out.println(t.plusHours(3));
Show answer
It prints 01:40. The plusMinutes(30) result is thrown away, so t is still 22:40. Adding 3 hours wraps past midnight to 01:40.
Exercise
Write an expression that is true when a LocalTime named now falls in a lunch break from 12:00 (inclusive) to 13:00 (exclusive).
Show answer
!now.isBefore(LocalTime.of(12, 0)) && now.isBefore(LocalTime.of(13, 0))
Exercise
A night shift runs from 22:00 to 06:00. Why would storing only the start and end as LocalTime values give a wrong answer if you tried to work out the shift length by subtracting the start from the end?
Show answer
LocalTime has no date. The end time 06:00 looks earlier than 22:00 on the clock, so a simple subtraction sees the shift as going backwards. To measure it correctly, attach dates with LocalDateTime (22:00 on one day, 06:00 on the next), or handle the midnight crossing yourself.