Menu
Coddy logo textTech

Period and Duration

Part of the Logic & Flow section of Coddy's Java journey — lesson 57 of 59.

Period represents a date-based amount of time (years, months, days), while Duration represents a time-based amount (hours, minutes, seconds).

Create a Period:

Period period = Period.of(1, 2, 15);
// 1 year, 2 months, 15 days

Create a Duration:

Duration duration = Duration.ofHours(2);
// 2 hours
Duration minutes = Duration.ofMinutes(90);
// 90 minutes

After executing the above code, period contains:

P1Y2M15D  // ISO-8601 format
challenge icon

Challenge

Easy

Create a method named calculateDifference that takes four arguments:

  1. A String (start) in format "yyyy-MM-dd HH:mm"
  2. A String (end) in format "yyyy-MM-dd HH:mm"
  3. A String (unit) either "period" or "duration"
  4. A String (format) either "full" or "simple"

The method should:

  1. Calculate the difference between start and end dates
  2. Return the difference in the specified format

Return messages should be:

  • If invalid dates: return "Invalid date format"
  • If invalid unit: return "Invalid unit"
  • If invalid format: return "Invalid format"
  • For period with "full" format: "Years: X, Months: Y, Days: Z"
  • For period with "simple" format: "XyYmZd"
  • For duration with "full" format: "Hours: X, Minutes: Y"
  • For duration with "simple" format: "XhYm"

Cheat sheet

Period represents date-based amounts (years, months, days), while Duration represents time-based amounts (hours, minutes, seconds).

Create a Period:

Period period = Period.of(1, 2, 15);
// 1 year, 2 months, 15 days

Create a Duration:

Duration duration = Duration.ofHours(2);
// 2 hours
Duration minutes = Duration.ofMinutes(90);
// 90 minutes

Period uses ISO-8601 format:

P1Y2M15D  // 1 year, 2 months, 15 days

Try it yourself

import java.util.Scanner;
import java.time.*;
import java.time.format.*;

public class Main {
    public static String calculateDifference(String start, String end, String unit, String format) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String start = scanner.nextLine();
        String end = scanner.nextLine();
        String unit = scanner.nextLine();
        String format = scanner.nextLine();
        
        System.out.println(calculateDifference(start, end, unit, format));
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow