Creating LocalTime Instances: now, of, parse
You'll learn the three main ways to create LocalTime objects in Java's modern Date and Time API.
What is LocalTime Again?
As you learned in the previous lesson, LocalTime represents time without any date information—just hours, minutes, seconds, and nanoseconds. Now let's see how to actually create these time objects.
Three Ways to Create LocalTime
1. now() - Current Time
The now() method captures the current time from your system clock:
LocalTime currentTime = LocalTime.now();
System.out.println(currentTime); // e.g., 14:23:45.123456789
Think of this as asking "What time is it right now?" The result includes nanosecond precision.
2. of() - Explicit Values
The of() method lets you specify exact time components. It has several overloaded versions:
LocalTime morning = LocalTime.of(9, 30); // 09:30:00
LocalTime precise = LocalTime.of(14, 30, 15); // 14:30:15
LocalTime nanos = LocalTime.of(14, 30, 15, 500); // 14:30:15.000000500
The parameters are: of(hour, minute), of(hour, minute, second), or of(hour, minute, second, nanosecond). This is like setting an alarm clock to a specific time.
3. parse() - From Strings
The parse() method converts ISO-8601 formatted strings (HH:mm:ss format) into LocalTime objects:
LocalTime afternoon = LocalTime.parse("14:30:00");
LocalTime withNanos = LocalTime.parse("14:30:00.123456789");
This is useful when reading time values from configuration files, user input, or databases.
Key Takeaway: Create LocalTime instances using now() for the current time, of() when you know the exact values, and parse() when converting from ISO-8601 formatted strings like "14:30:00".