Menu
Coddy logo textTech

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:30
challenge icon

Challenge

Easy

Create a method named processTime that takes four arguments:

  1. A String (timeStr) in format "HH:mm"
  2. An integer (amount) to add or subtract
  3. A String (unit) either "hours" or "minutes"
  4. A String (operation) either "add" or "subtract"

The method should:

  1. Parse the input time string
  2. Perform the specified operation
  3. 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:30

Try 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));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow