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 daysCreate a Duration:
Duration duration = Duration.ofHours(2);
// 2 hours
Duration minutes = Duration.ofMinutes(90);
// 90 minutesAfter executing the above code, period contains:
P1Y2M15D // ISO-8601 formatChallenge
EasyCreate a method named calculateDifference that takes four arguments:
- A String (
start) in format "yyyy-MM-dd HH:mm" - A String (
end) in format "yyyy-MM-dd HH:mm" - A String (
unit) either "period" or "duration" - A String (
format) either "full" or "simple"
The method should:
- Calculate the difference between start and end dates
- 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 daysCreate a Duration:
Duration duration = Duration.ofHours(2);
// 2 hours
Duration minutes = Duration.ofMinutes(90);
// 90 minutesPeriod uses ISO-8601 format:
P1Y2M15D // 1 year, 2 months, 15 daysTry 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));
}
}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