LocalTime Operations
Part of the Logic & Flow section of Coddy's Java journey — lesson 55 of 59.
LocalTime in Java represents a time without a date or timezone. It's useful for working with time-of-day values like opening hours or schedules.
Create current time:
LocalTime now = LocalTime.now();Create a specific time:
LocalTime time = LocalTime.of(14, 30);
// 14:30 (2:30 PM)After executing the above code, time contains:
14:30
Add or subtract time:
LocalTime time = LocalTime.of(14, 30);
LocalTime later = time.plusMinutes(45); // 15:15
LocalTime earlier = time.minusHours(1); // 13:30Challenge
EasyCreate a method named processTime that takes four arguments:
- A String (
timeStr) in format "HH:mm" - An integer (
amount) to add or subtract - A String (
unit) either "hours" or "minutes" - A String (
operation) either "add" or "subtract"
The method should:
- Parse the input time string
- Perform the specified operation
- Return formatted information about the result
Return messages should be:
- If invalid time format: return "Invalid time format"
- If invalid unit: return "Invalid unit"
- If invalid operation: return "Invalid operation"
- For success: return "Original: [time], New: [new_time]"
Cheat sheet
LocalTime represents a time without a date or timezone in Java.
Create current time:
LocalTime now = LocalTime.now();Create a specific time:
LocalTime time = LocalTime.of(14, 30); // 14:30 (2:30 PM)Add or subtract time:
LocalTime time = LocalTime.of(14, 30);
LocalTime later = time.plusMinutes(45); // 15:15
LocalTime earlier = time.minusHours(1); // 13:30Try it yourself
import java.util.Scanner;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Main {
public static String processTime(String timeStr, int amount, String unit, String operation) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String timeStr = scanner.nextLine();
int amount = Integer.parseInt(scanner.nextLine());
String unit = scanner.nextLine();
String operation = scanner.nextLine();
System.out.println(processTime(timeStr, amount, unit, operation));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet10Date and Time
LocalDate BasicsLocalTime OperationsLocalDateTime UsagePeriod and DurationDate FormattingTime Zone Handling2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap