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 formatMeasure the gap between two dates with Period.between(). It takes two LocalDate values and splits the gap into years, months and days:
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate end = LocalDate.of(2025, 3, 20);
Period p = Period.between(start, end);
p.getYears(); // 1
p.getMonths(); // 2
p.getDays(); // 5getDays() returns only the days left over after the whole years and months, not the total number of days between the two dates. A LocalDateTime gives you its date with toLocalDate().
Measure the gap between two times with Duration.between(), which takes two LocalDateTime (or LocalTime) values:
LocalDateTime from = LocalDateTime.of(2024, 3, 15, 10, 30);
LocalDateTime to = LocalDateTime.of(2024, 3, 15, 14, 45);
Duration d = Duration.between(from, to);
d.toHours(); // 4
d.toMinutes(); // 255
d.toMinutesPart(); // 15toMinutes() counts the whole gap in minutes, hours included. toMinutesPart() gives the minutes left over after the whole hours, so this gap is 4 hours and 15 minutes.
Challenge
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", where Y is the minutes left over after the whole hours
- For duration with "simple" format: "XhYm"
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));
}
}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 - HashMapPractice on your own: Online Java compiler