diff --git a/concepts/durations-and-periods/.meta/config.json b/concepts/durations-and-periods/.meta/config.json new file mode 100644 index 000000000..0c35ecea1 --- /dev/null +++ b/concepts/durations-and-periods/.meta/config.json @@ -0,0 +1,7 @@ +{ + "blurb": "Represent amounts of time with Java's date-based `Period` and time-based `Duration` classes.", + "authors": [ + "rabestro" + ], + "contributors": [] +} diff --git a/concepts/durations-and-periods/about.md b/concepts/durations-and-periods/about.md new file mode 100644 index 000000000..d082d7b7e --- /dev/null +++ b/concepts/durations-and-periods/about.md @@ -0,0 +1,323 @@ +# About + +Classes like `LocalDate` and `LocalDateTime` describe a _point_ in time. +The `java.time` package also has two classes that describe an _amount_ of time: + +- [`Period`][period-docs] is a date-based amount of time in years, months and days, such as "2 months and 5 days". +- [`Duration`][duration-docs] is a time-based amount of time in seconds and nanoseconds, such as "1 hour and 30 minutes". + +The difference matters because calendar units do not have a fixed length. +A month can have 28, 29, 30 or 31 days, so "one month" is not a fixed number of seconds. +A `Period` follows the calendar, while a `Duration` measures exact time. + +| | `Period` | `Duration` | +| --- | --- | --- | +| Stores | years, months and days | seconds and nanoseconds | +| Used with | `LocalDate` | `LocalTime`, `LocalDateTime`, `Instant` | +| Example | "the membership lasts 1 month" | "the visit lasted 95 minutes" | +| `toString()` | `P1Y2M15D` | `PT1H35M` | + +Both classes are immutable. +Methods such as `plusDays()` or `multipliedBy()` return a _new_ instance and leave the original unchanged. + +## `Period` + +### Creating a period + +```java +Period.ofDays(10); +// => P10D + +Period.ofWeeks(2); +// => P14D + +Period.ofMonths(3); +// => P3M + +Period.of(1, 2, 15); +// => P1Y2M15D +``` + +The result of `toString()` uses the [ISO-8601 duration format][iso-8601-durations]: `P` followed by the number of years (`Y`), months (`M`) and days (`D`). +There are no weeks in a `Period`: `Period.ofWeeks(2)` is stored as 14 days. +The same notation can be parsed back with `Period.parse()`: + +```java +Period.parse("P1Y2M15D"); +// => P1Y2M15D +``` + +### Adding a period to a date + +A period is added to or subtracted from a date with `plus()` and `minus()`: + +```java +LocalDate date = LocalDate.of(2024, 3, 10); + +date.plus(Period.ofMonths(2)); +// => 2024-05-10 + +date.minus(Period.ofDays(10)); +// => 2024-02-29 +``` + +The years are added first, then the months and then the days. +When adding years or months lands on a day that does not exist, the result is moved back to the last valid day of that month: + +```java +LocalDate.of(2025, 1, 31).plus(Period.ofMonths(1)); +// => 2025-02-28 + +LocalDate.of(2024, 2, 29).plus(Period.ofYears(1)); +// => 2025-02-28 +``` + +This also means that adding a period and then subtracting it again does not always give back the original date: + +```java +LocalDate.of(2025, 1, 31).plus(Period.ofMonths(1)).minus(Period.ofMonths(1)); +// => 2025-01-28 +``` + +### The period between two dates + +`Period.between()` returns the period from one date (inclusive) to another (exclusive). +The same result is available as `LocalDate.until()`: + +```java +LocalDate start = LocalDate.of(2023, 3, 10); +LocalDate end = LocalDate.of(2024, 5, 25); + +Period.between(start, end); +// => P1Y2M15D + +start.until(end); +// => P1Y2M15D +``` + +The parts of a period are available through `getYears()`, `getMonths()` and `getDays()`. +These parts are independent of each other: `getDays()` returns only the days part, not the total number of days. +`toTotalMonths()` returns the years and months combined as a number of months, but there is no method for the total number of days, because that depends on which months are involved. + +```java +Period period = Period.between(LocalDate.of(2024, 1, 15), LocalDate.of(2024, 3, 20)); +// => P2M5D + +period.getDays(); +// => 5 + +period.toTotalMonths(); +// => 2 +``` + +### Normalizing a period + +A period created with a factory method keeps its units exactly as given, and `equals()` compares the units one by one. +`normalized()` rolls months over into years, but it leaves the days alone: + +```java +Period.ofMonths(14); +// => P14M + +Period.ofMonths(14).equals(Period.of(1, 2, 0)); +// => false + +Period.ofMonths(14).normalized(); +// => P1Y2M + +Period.ofDays(45).normalized(); +// => P45D +``` + +## Counting units with `ChronoUnit` + +To get the total number of a single unit between two points in time, use the `between()` method on one of the constants of [`ChronoUnit`][chronounit-docs]: + +```java +LocalDate start = LocalDate.of(2024, 1, 15); +LocalDate end = LocalDate.of(2024, 3, 20); + +ChronoUnit.DAYS.between(start, end); +// => 65 + +ChronoUnit.WEEKS.between(start, end); +// => 9 + +ChronoUnit.MONTHS.between(start, end); +// => 2 +``` + +Only complete units are counted, and the result is negative when the second argument is before the first one: + +```java +ChronoUnit.DAYS.between(end, start); +// => -65 +``` + +`ChronoUnit` works with time-based units and date-times too: + +```java +ChronoUnit.MINUTES.between( + LocalDateTime.of(2024, 3, 10, 18, 5), + LocalDateTime.of(2024, 3, 10, 19, 40)); +// => 95 +``` + +## `Duration` + +### Creating a duration + +```java +Duration.ofMinutes(90); +// => PT1H30M + +Duration.ofSeconds(3725); +// => PT1H2M5S + +Duration.ofDays(2); +// => PT48H + +Duration.ofHours(2).plusMinutes(15); +// => PT2H15M +``` + +In the ISO-8601 notation, the `T` separates the date part from the time part. +A `Duration` has no date part, so its `toString()` always starts with `PT`. +`Duration.ofDays()` treats a day as exactly 24 hours. + +A duration can also be parsed with `Duration.parse()`: + +```java +Duration.parse("PT1H30M"); +// => PT1H30M +``` + +### Adding a duration to a time + +A duration is added to or subtracted from a `LocalTime`, a `LocalDateTime` or an `Instant` with `plus()` and `minus()`: + +```java +LocalDateTime start = LocalDateTime.of(2024, 3, 10, 22, 30); + +start.plus(Duration.ofMinutes(90)); +// => 2024-03-11T00:00 + +LocalTime.of(23, 0).plus(Duration.ofHours(2)); +// => 01:00 +``` + +A `LocalTime` wraps around midnight, as the last example shows. + +A `LocalDate` has no time, so it cannot be combined with a `Duration`: + +```java +LocalDate.of(2024, 3, 10).plus(Duration.ofHours(1)); +// => throws UnsupportedTemporalTypeException +``` + +### The duration between two times + +`Duration.between()` returns the exact amount of time between two times or date-times: + +```java +LocalDateTime checkIn = LocalDateTime.of(2024, 3, 10, 18, 5); +LocalDateTime checkOut = LocalDateTime.of(2024, 3, 10, 19, 40); + +Duration.between(checkIn, checkOut); +// => PT1H35M + +Duration.between(checkOut, checkIn); +// => PT-1H-35M +``` + +`Duration.between()` does not accept two `LocalDate` values, because a date has no seconds to measure: + +```java +Duration.between(LocalDate.of(2024, 1, 15), LocalDate.of(2024, 3, 20)); +// => throws UnsupportedTemporalTypeException +``` + +Use `Period.between()` or `ChronoUnit.DAYS.between()` for dates instead. + +### Converting a duration + +The `toXxx()` methods convert a duration to a _total_ amount of a single unit, rounded down: + +```java +Duration duration = Duration.ofSeconds(5730); // 1 hour, 35 minutes and 30 seconds + +duration.toHours(); +// => 1 + +duration.toMinutes(); +// => 95 + +duration.toSeconds(); +// => 5730 +``` + +The `toXxxPart()` methods split a duration into its parts, as on a clock: + +```java +Duration duration = Duration.ofSeconds(5730); + +duration.toHoursPart(); +// => 1 + +duration.toMinutesPart(); +// => 35 + +duration.toSecondsPart(); +// => 30 +``` + +`toHoursPart()` stops at 23, because the hours above that are counted by `toDaysPart()`. + +### Comparing and calculating with durations + +Durations can be compared with `compareTo()`, and checked with `isZero()` and `isNegative()`: + +```java +Duration visit = Duration.ofMinutes(95); +Duration limit = Duration.ofHours(2); + +visit.compareTo(limit) > 0; +// => false + +Duration.between(LocalTime.of(10, 0), LocalTime.of(9, 0)).isNegative(); +// => true +``` + +They also support arithmetic, such as `plus()`, `minus()`, `multipliedBy()` and `dividedBy()`: + +```java +Duration.ofMinutes(20).multipliedBy(3); +// => PT1H + +Duration.ofHours(2).dividedBy(Duration.ofMinutes(15)); +// => 8 +``` + +## `Period` or `Duration`? + +For local dates and times, the choice is usually made for you: a date has no time to measure, and a time has no calendar. +The difference becomes visible with time zones. +When the clocks move forward for daylight saving time, a calendar day is only 23 hours long: + +```java +ZonedDateTime noon = ZonedDateTime.of(2025, 3, 29, 12, 0, 0, 0, ZoneId.of("Europe/Amsterdam")); + +noon.plus(Period.ofDays(1)); +// => 2025-03-30T12:00+02:00[Europe/Amsterdam] + +noon.plus(Duration.ofDays(1)); +// => 2025-03-30T13:00+02:00[Europe/Amsterdam] +``` + +Adding a `Period` of one day keeps the time of day, while adding a `Duration` of one day adds exactly 24 hours. +Use a `Period` for amounts people think about in calendar terms ("the same time next month") and a `Duration` for elapsed time ("the parking ticket is valid for 2 hours"). + +[period-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Period.html +[duration-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html +[chronounit-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html +[iso-8601-durations]: https://en.wikipedia.org/wiki/ISO_8601#Durations diff --git a/concepts/durations-and-periods/introduction.md b/concepts/durations-and-periods/introduction.md new file mode 100644 index 000000000..f57d468b6 --- /dev/null +++ b/concepts/durations-and-periods/introduction.md @@ -0,0 +1,155 @@ +# Introduction + +Classes like `LocalDate` and `LocalDateTime` describe a _point_ in time. +The `java.time` package also has two classes that describe an _amount_ of time: + +- `java.time.Period` is an amount of time in years, months and days, such as "2 months and 5 days". +- `java.time.Duration` is an amount of time in seconds and nanoseconds, such as "1 hour and 30 minutes". + +A `Period` follows the calendar, so it is used with dates. +A `Duration` measures exact time, so it is used with times and date-times. + +```exercism/note +Like the other `java.time` classes, `Period` and `Duration` are immutable. +Methods that look like they change them return a _new_ instance instead. +``` + +## `Period` + +A `Period` is created with one of its static factory methods: + +```java +Period.ofDays(10); +// => P10D + +Period.ofMonths(3); +// => P3M + +Period.of(1, 2, 15); +// => P1Y2M15D +``` + +The result of `toString()` uses the [ISO-8601][iso-8601-durations] notation: `P` (for "period") followed by the number of years (`Y`), months (`M`) and days (`D`). + +A period can be added to or subtracted from a date: + +```java +LocalDate date = LocalDate.of(2024, 3, 10); + +date.plus(Period.ofMonths(2)); +// => 2024-05-10 + +date.minus(Period.ofDays(10)); +// => 2024-02-29 +``` + +Because months have different lengths, adding months can land on a day that does not exist. +In that case the result is moved back to the last valid day of the month: + +```java +LocalDate.of(2025, 1, 31).plus(Period.ofMonths(1)); +// => 2025-02-28 +``` + +`Period.between()` returns the period from one date (inclusive) to another (exclusive): + +```java +LocalDate start = LocalDate.of(2023, 3, 10); +LocalDate end = LocalDate.of(2024, 5, 25); + +Period period = Period.between(start, end); +// => P1Y2M15D + +period.getYears(); +// => 1 +period.getMonths(); +// => 2 +period.getDays(); +// => 15 +``` + +## Counting units with `ChronoUnit` + +A `Period` keeps its years, months and days apart. +So `getDays()` returns only the days _part_ of the period, not the total number of days. +To count the total number of a single unit between two dates, use the `between()` method of [`java.time.temporal.ChronoUnit`][chronounit-docs]: + +```java +LocalDate start = LocalDate.of(2024, 1, 15); +LocalDate end = LocalDate.of(2024, 3, 20); + +Period.between(start, end); +// => P2M5D + +Period.between(start, end).getDays(); +// => 5 + +ChronoUnit.DAYS.between(start, end); +// => 65 +``` + +The result is negative when the second date is before the first one: + +```java +ChronoUnit.DAYS.between(end, start); +// => -65 +``` + +## `Duration` + +A `Duration` is also created with static factory methods: + +```java +Duration.ofMinutes(90); +// => PT1H30M + +Duration.ofHours(2).plusMinutes(15); +// => PT2H15M +``` + +In the ISO-8601 notation, the `T` separates the date part from the time part, which is why durations are written as `PT...`. + +A duration can be added to or subtracted from a date-time: + +```java +LocalDateTime start = LocalDateTime.of(2024, 3, 10, 22, 30); + +start.plus(Duration.ofMinutes(90)); +// => 2024-03-11T00:00 +``` + +`Duration.between()` returns the exact amount of time between two date-times: + +```java +LocalDateTime checkIn = LocalDateTime.of(2024, 3, 10, 18, 5); +LocalDateTime checkOut = LocalDateTime.of(2024, 3, 10, 19, 40); + +Duration.between(checkIn, checkOut); +// => PT1H35M +``` + +A duration can be converted to a single unit with methods such as `toHours()`, `toMinutes()` and `toSeconds()`. +These return the _total_ amount in that unit, rounded down: + +```java +Duration duration = Duration.ofMinutes(95); + +duration.toHours(); +// => 1 +duration.toMinutes(); +// => 95 +``` + +To split a duration into its parts, as on a clock, use the `toXxxPart()` methods instead: + +```java +Duration duration = Duration.ofMinutes(95); + +duration.toHoursPart(); +// => 1 +duration.toMinutesPart(); +// => 35 +``` + +[iso-8601-durations]: https://en.wikipedia.org/wiki/ISO_8601#Durations +[chronounit-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html diff --git a/concepts/durations-and-periods/links.json b/concepts/durations-and-periods/links.json new file mode 100644 index 000000000..9f4c0cd98 --- /dev/null +++ b/concepts/durations-and-periods/links.json @@ -0,0 +1,18 @@ +[ + { + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Period.html", + "description": "Period class documentation" + }, + { + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html", + "description": "Duration class documentation" + }, + { + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html", + "description": "ChronoUnit enum documentation" + }, + { + "url": "https://dev.java/learn/date-time/period-duration/", + "description": "Period and Duration tutorial on dev.java" + } +] diff --git a/config.json b/config.json index 37eb58513..faa193a10 100644 --- a/config.json +++ b/config.json @@ -341,6 +341,19 @@ "enums" ], "status": "active" + }, + { + "slug": "gym-front-desk", + "name": "Gym Front Desk", + "uuid": "6553f255-154f-441d-a6e1-a428434f9653", + "concepts": [ + "durations-and-periods" + ], + "prerequisites": [ + "datetime", + "strings" + ], + "status": "active" } ], "practice": [ @@ -593,11 +606,13 @@ "name": "Gigasecond", "uuid": "bf1641c8-dc0d-4d38-9cfe-b4c132ea3553", "practices": [ - "datetime" + "datetime", + "durations-and-periods" ], "prerequisites": [ "datetime", - "numbers" + "numbers", + "durations-and-periods" ], "difficulty": 3 }, @@ -2211,6 +2226,11 @@ "uuid": "cc7a06d1-ddb3-4722-88a5-f762254d664e", "slug": "temporal-adjusters", "name": "Temporal Adjusters" + }, + { + "uuid": "16500ebe-104e-44c3-84b3-3126a49bdb89", + "slug": "durations-and-periods", + "name": "Durations and Periods" } ], "key_features": [ diff --git a/exercises/concept/gym-front-desk/.docs/hints.md b/exercises/concept/gym-front-desk/.docs/hints.md new file mode 100644 index 000000000..277c62016 --- /dev/null +++ b/exercises/concept/gym-front-desk/.docs/hints.md @@ -0,0 +1,46 @@ +# Hints + +## General + +- A [`Period`][period-docs] is an amount of time in years, months and days, and is used with dates. +- A [`Duration`][duration-docs] is an amount of time in seconds and nanoseconds, and is used with times and date-times. +- Both classes are immutable: their methods return a new instance and leave the original unchanged. + +## 1. Work out when a membership ends + +- There is a [factory method][period-ofmonths] that creates a `Period` of a number of months. +- A period can be added to a date with the date's [`plus()`][localdate-plus] method. +- `plus()` already moves a day that does not exist back to the last day of the month, so you do not need to handle it yourself. + +## 2. Show how long a membership lasts + +- There is a [static method][period-between] on `Period` that returns the period between two dates. + +## 3. Count the days left on a membership + +- The `getDays()` method of a `Period` only returns the days part of the period, not the total number of days. +- The [`between()`][chronounit-between] method of a [`ChronoUnit`][chronounit-docs] constant counts the total number of that unit between two dates. +- [`Math.max()`][math-max] returns the larger of two numbers. + +## 4. Measure a visit + +- There is a [static method][duration-between] on `Duration` that returns the duration between two date-times. + +## 5. Print a visit on the receipt + +- There is a [method][duration-tohours] that returns the total number of hours in a duration. +- There is a [method][duration-tominutespart] that returns only the minutes part of a duration, between 0 and 59. +- [`String.format()`][string-format] with the format specifier `%02d` writes a number with at least two digits, padding it with a leading zero. + +[period-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Period.html +[duration-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html +[period-ofmonths]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Period.html#ofMonths(int) +[localdate-plus]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDate.html#plus(java.time.temporal.TemporalAmount) +[period-between]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Period.html#between(java.time.LocalDate,java.time.LocalDate) +[chronounit-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html +[chronounit-between]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html#between(java.time.temporal.Temporal,java.time.temporal.Temporal) +[math-max]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Math.html#max(long,long) +[duration-between]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html#between(java.time.temporal.Temporal,java.time.temporal.Temporal) +[duration-tohours]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html#toHours() +[duration-tominutespart]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html#toMinutesPart() +[string-format]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html#format(java.lang.String,java.lang.Object...) diff --git a/exercises/concept/gym-front-desk/.docs/instructions.md b/exercises/concept/gym-front-desk/.docs/instructions.md new file mode 100644 index 000000000..4c7a39df8 --- /dev/null +++ b/exercises/concept/gym-front-desk/.docs/instructions.md @@ -0,0 +1,76 @@ +# Instructions + +You have just started working at the front desk of a climbing gym. +Members buy memberships for a number of months and check in and out every time they visit. +The manager has asked you to write a helper that answers the questions members ask most often. + +## 1. Work out when a membership ends + +A membership that starts on a given date ends on the same day of the month, the given number of months later. +When that day does not exist in the end month, the membership ends on the last day of that month instead. + +Implement the `FrontDesk.membershipEnd()` method that takes the start date of a membership and its number of months, and returns the date on which it ends: + +```java +FrontDesk frontDesk = new FrontDesk(); +frontDesk.membershipEnd(LocalDate.of(2024, 3, 10), 1); +// => LocalDate.of(2024, 4, 10) +frontDesk.membershipEnd(LocalDate.of(2025, 1, 31), 1); +// => LocalDate.of(2025, 2, 28) +``` + +## 2. Show how long a membership lasts + +On the membership card, the gym prints how long the membership lasts in years, months and days. + +Implement the `FrontDesk.membershipLength()` method that takes the start date and the end date of a membership, and returns the length of the membership as a `Period`: + +```java +FrontDesk frontDesk = new FrontDesk(); +frontDesk.membershipLength(LocalDate.of(2023, 3, 10), LocalDate.of(2024, 5, 25)); +// => Period.of(1, 2, 15) +``` + +## 3. Count the days left on a membership + +Members often ask how many days they have left before their membership ends. + +Implement the `FrontDesk.daysLeft()` method that takes today's date and the end date of a membership, and returns the total number of days from today until the end date. +When the end date is today or has already passed, there are no days left, so the method returns `0`: + +```java +FrontDesk frontDesk = new FrontDesk(); +frontDesk.daysLeft(LocalDate.of(2024, 1, 15), LocalDate.of(2024, 3, 20)); +// => 65 +frontDesk.daysLeft(LocalDate.of(2024, 4, 2), LocalDate.of(2024, 3, 20)); +// => 0 +``` + +## 4. Measure a visit + +The gym is open around the clock, and the turnstile records the date and time when a member checks in and out. + +Implement the `FrontDesk.visitDuration()` method that takes the check-in and check-out date-times of a visit, and returns how long the visit lasted as a `Duration`: + +```java +FrontDesk frontDesk = new FrontDesk(); +frontDesk.visitDuration(LocalDateTime.of(2024, 3, 10, 23, 30), LocalDateTime.of(2024, 3, 11, 1, 15)); +// => Duration.ofMinutes(105) +``` + +## 5. Print a visit on the receipt + +The receipt shows the length of a visit in hours and minutes, like `1h 35m`. +The minutes are always written with two digits, any seconds are left out, and the hours are not limited to a single day. + +Implement the `FrontDesk.formatVisit()` method that takes the duration of a visit and returns it in this format: + +```java +FrontDesk frontDesk = new FrontDesk(); +frontDesk.formatVisit(Duration.ofMinutes(95)); +// => "1h 35m" +frontDesk.formatVisit(Duration.ofHours(2).plusMinutes(5)); +// => "2h 05m" +frontDesk.formatVisit(Duration.ofHours(26).plusMinutes(10)); +// => "26h 10m" +``` diff --git a/exercises/concept/gym-front-desk/.docs/introduction.md b/exercises/concept/gym-front-desk/.docs/introduction.md new file mode 100644 index 000000000..b9676bdc2 --- /dev/null +++ b/exercises/concept/gym-front-desk/.docs/introduction.md @@ -0,0 +1,157 @@ +# Introduction + +## Durations and Periods + +Classes like `LocalDate` and `LocalDateTime` describe a _point_ in time. +The `java.time` package also has two classes that describe an _amount_ of time: + +- `java.time.Period` is an amount of time in years, months and days, such as "2 months and 5 days". +- `java.time.Duration` is an amount of time in seconds and nanoseconds, such as "1 hour and 30 minutes". + +A `Period` follows the calendar, so it is used with dates. +A `Duration` measures exact time, so it is used with times and date-times. + +```exercism/note +Like the other `java.time` classes, `Period` and `Duration` are immutable. +Methods that look like they change them return a _new_ instance instead. +``` + +### `Period` + +A `Period` is created with one of its static factory methods: + +```java +Period.ofDays(10); +// => P10D + +Period.ofMonths(3); +// => P3M + +Period.of(1, 2, 15); +// => P1Y2M15D +``` + +The result of `toString()` uses the [ISO-8601][iso-8601-durations] notation: `P` (for "period") followed by the number of years (`Y`), months (`M`) and days (`D`). + +A period can be added to or subtracted from a date: + +```java +LocalDate date = LocalDate.of(2024, 3, 10); + +date.plus(Period.ofMonths(2)); +// => 2024-05-10 + +date.minus(Period.ofDays(10)); +// => 2024-02-29 +``` + +Because months have different lengths, adding months can land on a day that does not exist. +In that case the result is moved back to the last valid day of the month: + +```java +LocalDate.of(2025, 1, 31).plus(Period.ofMonths(1)); +// => 2025-02-28 +``` + +`Period.between()` returns the period from one date (inclusive) to another (exclusive): + +```java +LocalDate start = LocalDate.of(2023, 3, 10); +LocalDate end = LocalDate.of(2024, 5, 25); + +Period period = Period.between(start, end); +// => P1Y2M15D + +period.getYears(); +// => 1 +period.getMonths(); +// => 2 +period.getDays(); +// => 15 +``` + +### Counting units with `ChronoUnit` + +A `Period` keeps its years, months and days apart. +So `getDays()` returns only the days _part_ of the period, not the total number of days. +To count the total number of a single unit between two dates, use the `between()` method of [`java.time.temporal.ChronoUnit`][chronounit-docs]: + +```java +LocalDate start = LocalDate.of(2024, 1, 15); +LocalDate end = LocalDate.of(2024, 3, 20); + +Period.between(start, end); +// => P2M5D + +Period.between(start, end).getDays(); +// => 5 + +ChronoUnit.DAYS.between(start, end); +// => 65 +``` + +The result is negative when the second date is before the first one: + +```java +ChronoUnit.DAYS.between(end, start); +// => -65 +``` + +### `Duration` + +A `Duration` is also created with static factory methods: + +```java +Duration.ofMinutes(90); +// => PT1H30M + +Duration.ofHours(2).plusMinutes(15); +// => PT2H15M +``` + +In the ISO-8601 notation, the `T` separates the date part from the time part, which is why durations are written as `PT...`. + +A duration can be added to or subtracted from a date-time: + +```java +LocalDateTime start = LocalDateTime.of(2024, 3, 10, 22, 30); + +start.plus(Duration.ofMinutes(90)); +// => 2024-03-11T00:00 +``` + +`Duration.between()` returns the exact amount of time between two date-times: + +```java +LocalDateTime checkIn = LocalDateTime.of(2024, 3, 10, 18, 5); +LocalDateTime checkOut = LocalDateTime.of(2024, 3, 10, 19, 40); + +Duration.between(checkIn, checkOut); +// => PT1H35M +``` + +A duration can be converted to a single unit with methods such as `toHours()`, `toMinutes()` and `toSeconds()`. +These return the _total_ amount in that unit, rounded down: + +```java +Duration duration = Duration.ofMinutes(95); + +duration.toHours(); +// => 1 +duration.toMinutes(); +// => 95 +``` + +To split a duration into its parts, as on a clock, use the `toXxxPart()` methods instead: + +```java +Duration duration = Duration.ofMinutes(95); + +duration.toHoursPart(); +// => 1 +duration.toMinutesPart(); +// => 35 +``` + +[iso-8601-durations]: https://en.wikipedia.org/wiki/ISO_8601#Durations +[chronounit-docs]: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/temporal/ChronoUnit.html diff --git a/exercises/concept/gym-front-desk/.docs/introduction.md.tpl b/exercises/concept/gym-front-desk/.docs/introduction.md.tpl new file mode 100644 index 000000000..37c7bb4fc --- /dev/null +++ b/exercises/concept/gym-front-desk/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:durations-and-periods} diff --git a/exercises/concept/gym-front-desk/.meta/config.json b/exercises/concept/gym-front-desk/.meta/config.json new file mode 100644 index 000000000..8f05733c0 --- /dev/null +++ b/exercises/concept/gym-front-desk/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "rabestro" + ], + "files": { + "solution": [ + "src/main/java/FrontDesk.java" + ], + "test": [ + "src/test/java/FrontDeskTest.java" + ], + "exemplar": [ + ".meta/src/reference/java/FrontDesk.java" + ], + "invalidator": [ + "build.gradle" + ] + }, + "blurb": "Learn about durations and periods by answering members' questions at the front desk of a climbing gym." +} diff --git a/exercises/concept/gym-front-desk/.meta/design.md b/exercises/concept/gym-front-desk/.meta/design.md new file mode 100644 index 000000000..2e908e9e9 --- /dev/null +++ b/exercises/concept/gym-front-desk/.meta/design.md @@ -0,0 +1,44 @@ +# Design + +## Learning objectives + +- Know the difference between the date-based `Period` and the time-based `Duration`. +- Know how to create a `Period` with its factory methods and add it to a `LocalDate` with `plus()`. +- Know that adding months clamps the result to the last valid day of the month. +- Know how to get the period between two dates with `Period.between()`. +- Know that `Period.getDays()` returns only the days part, and how to count the total number of days with `ChronoUnit.DAYS.between()`. +- Know how to get the duration between two date-times with `Duration.between()`. +- Know the difference between the `toXxx()` methods (total amount in a unit) and the `toXxxPart()` methods (part of the duration) of `Duration`. + +## Out of scope + +- Time zones, offsets and `ZonedDateTime`. +- `Instant` and `Clock`. +- Parsing and formatting the ISO-8601 representation of periods and durations. +- `Period.normalized()` and `Duration` arithmetic such as `multipliedBy()` and `dividedBy()`. +- Anything depending on the current date (`LocalDate.now()`). + +## Concepts + +- `durations-and-periods` + +## Prerequisites + +This exercise's prerequisites Concepts are: + +- `datetime`: creating and using `LocalDate` and `LocalDateTime`. +- `strings`: building the receipt text. + +## Analyzer + +This exercise could benefit from the following rules in the [analyzer]: + +- `essential`: If `membershipEnd()` uses `plusDays()` or adds a fixed number of days per month, instruct the student to add a `Period` of months instead. +- `essential`: If `daysLeft()` uses `Period.between(...).getDays()`, point out that it only returns the days part of the period and suggest `ChronoUnit.DAYS.between()`. +- `actionable`: If `formatVisit()` uses `toHoursPart()`, point out that it stops at 23 hours and suggest `toHours()`. +- `actionable`: If `formatVisit()` computes the minutes with `toMinutes() % 60`, suggest `toMinutesPart()`. + +If the solution does not receive any of the above feedback, it must be exemplar. +Leave a `celebratory` comment to celebrate the success! + +[analyzer]: https://github.com/exercism/java-analyzer diff --git a/exercises/concept/gym-front-desk/.meta/src/reference/java/FrontDesk.java b/exercises/concept/gym-front-desk/.meta/src/reference/java/FrontDesk.java new file mode 100644 index 000000000..495917036 --- /dev/null +++ b/exercises/concept/gym-front-desk/.meta/src/reference/java/FrontDesk.java @@ -0,0 +1,28 @@ +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Period; +import java.time.temporal.ChronoUnit; + +class FrontDesk { + + public LocalDate membershipEnd(LocalDate start, int months) { + return start.plus(Period.ofMonths(months)); + } + + public Period membershipLength(LocalDate start, LocalDate end) { + return Period.between(start, end); + } + + public long daysLeft(LocalDate today, LocalDate end) { + return Math.max(0, ChronoUnit.DAYS.between(today, end)); + } + + public Duration visitDuration(LocalDateTime checkIn, LocalDateTime checkOut) { + return Duration.between(checkIn, checkOut); + } + + public String formatVisit(Duration visit) { + return String.format("%dh %02dm", visit.toHours(), visit.toMinutesPart()); + } +} diff --git a/exercises/concept/gym-front-desk/build.gradle b/exercises/concept/gym-front-desk/build.gradle new file mode 100644 index 000000000..dd3862eb9 --- /dev/null +++ b/exercises/concept/gym-front-desk/build.gradle @@ -0,0 +1,25 @@ +plugins { + id "java" +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation platform("org.junit:junit-bom:5.10.0") + testImplementation "org.junit.jupiter:junit-jupiter" + testImplementation "org.assertj:assertj-core:3.25.1" + + testRuntimeOnly "org.junit.platform:junit-platform-launcher" +} + +test { + useJUnitPlatform() + + testLogging { + exceptionFormat = "full" + showStandardStreams = true + events = ["passed", "failed", "skipped"] + } +} diff --git a/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..b1b8ef56b Binary files /dev/null and b/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..6394b4647 --- /dev/null +++ b/exercises/concept/gym-front-desk/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/gym-front-desk/gradlew b/exercises/concept/gym-front-desk/gradlew new file mode 100755 index 000000000..b9bb139f7 --- /dev/null +++ b/exercises/concept/gym-front-desk/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/exercises/concept/gym-front-desk/gradlew.bat b/exercises/concept/gym-front-desk/gradlew.bat new file mode 100644 index 000000000..24c62d56f --- /dev/null +++ b/exercises/concept/gym-front-desk/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/exercises/concept/gym-front-desk/src/main/java/FrontDesk.java b/exercises/concept/gym-front-desk/src/main/java/FrontDesk.java new file mode 100644 index 000000000..8e74f9a61 --- /dev/null +++ b/exercises/concept/gym-front-desk/src/main/java/FrontDesk.java @@ -0,0 +1,27 @@ +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Period; + +class FrontDesk { + + public LocalDate membershipEnd(LocalDate start, int months) { + throw new UnsupportedOperationException("Please implement the FrontDesk.membershipEnd() method"); + } + + public Period membershipLength(LocalDate start, LocalDate end) { + throw new UnsupportedOperationException("Please implement the FrontDesk.membershipLength() method"); + } + + public long daysLeft(LocalDate today, LocalDate end) { + throw new UnsupportedOperationException("Please implement the FrontDesk.daysLeft() method"); + } + + public Duration visitDuration(LocalDateTime checkIn, LocalDateTime checkOut) { + throw new UnsupportedOperationException("Please implement the FrontDesk.visitDuration() method"); + } + + public String formatVisit(Duration visit) { + throw new UnsupportedOperationException("Please implement the FrontDesk.formatVisit() method"); + } +} diff --git a/exercises/concept/gym-front-desk/src/test/java/FrontDeskTest.java b/exercises/concept/gym-front-desk/src/test/java/FrontDeskTest.java new file mode 100644 index 000000000..06a6bdef3 --- /dev/null +++ b/exercises/concept/gym-front-desk/src/test/java/FrontDeskTest.java @@ -0,0 +1,208 @@ +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Period; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FrontDeskTest { + + private final FrontDesk frontDesk = new FrontDesk(); + + @Test + @Tag("task:1") + @DisplayName("A one-month membership ends on the same day next month") + public void testMembershipEndOneMonth() { + var expected = LocalDate.of(2024, 4, 10); + + assertThat(frontDesk.membershipEnd(LocalDate.of(2024, 3, 10), 1)).isEqualTo(expected); + } + + @Test + @Tag("task:1") + @DisplayName("A twelve-month membership ends on the same day next year") + public void testMembershipEndTwelveMonths() { + var expected = LocalDate.of(2025, 3, 10); + + assertThat(frontDesk.membershipEnd(LocalDate.of(2024, 3, 10), 12)).isEqualTo(expected); + } + + @Test + @Tag("task:1") + @DisplayName("A membership starting on January 31st ends on the last day of February") + public void testMembershipEndClampedToEndOfFebruary() { + var expected = LocalDate.of(2025, 2, 28); + + assertThat(frontDesk.membershipEnd(LocalDate.of(2025, 1, 31), 1)).isEqualTo(expected); + } + + @Test + @Tag("task:1") + @DisplayName("A membership starting on January 31st ends on February 29th in a leap year") + public void testMembershipEndClampedToEndOfFebruaryInLeapYear() { + var expected = LocalDate.of(2024, 2, 29); + + assertThat(frontDesk.membershipEnd(LocalDate.of(2024, 1, 31), 1)).isEqualTo(expected); + } + + @Test + @Tag("task:1") + @DisplayName("A three-month membership starting on August 31st ends on November 30th") + public void testMembershipEndClampedToEndOfNovember() { + var expected = LocalDate.of(2024, 11, 30); + + assertThat(frontDesk.membershipEnd(LocalDate.of(2024, 8, 31), 3)).isEqualTo(expected); + } + + @Test + @Tag("task:2") + @DisplayName("Membership length in years, months and days") + public void testMembershipLengthYearsMonthsAndDays() { + var expected = Period.of(1, 2, 15); + + assertThat(frontDesk.membershipLength(LocalDate.of(2023, 3, 10), LocalDate.of(2024, 5, 25))) + .isEqualTo(expected); + } + + @Test + @Tag("task:2") + @DisplayName("Membership length in months and days") + public void testMembershipLengthMonthsAndDays() { + var expected = Period.of(0, 2, 5); + + assertThat(frontDesk.membershipLength(LocalDate.of(2024, 1, 15), LocalDate.of(2024, 3, 20))) + .isEqualTo(expected); + } + + @Test + @Tag("task:2") + @DisplayName("Membership length of exactly one year") + public void testMembershipLengthExactlyOneYear() { + var expected = Period.ofYears(1); + + assertThat(frontDesk.membershipLength(LocalDate.of(2024, 3, 10), LocalDate.of(2025, 3, 10))) + .isEqualTo(expected); + } + + @Test + @Tag("task:2") + @DisplayName("Membership length is zero when it starts and ends on the same day") + public void testMembershipLengthZero() { + assertThat(frontDesk.membershipLength(LocalDate.of(2024, 3, 10), LocalDate.of(2024, 3, 10))) + .isEqualTo(Period.ZERO); + } + + @Test + @Tag("task:3") + @DisplayName("Days left within the same month") + public void testDaysLeftSameMonth() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 3, 10), LocalDate.of(2024, 3, 25))).isEqualTo(15); + } + + @Test + @Tag("task:3") + @DisplayName("Days left counts every day across several months") + public void testDaysLeftAcrossMonths() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 1, 15), LocalDate.of(2024, 3, 20))).isEqualTo(65); + } + + @Test + @Tag("task:3") + @DisplayName("Days left across the end of the year") + public void testDaysLeftAcrossYearEnd() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 12, 20), LocalDate.of(2025, 1, 10))).isEqualTo(21); + } + + @Test + @Tag("task:3") + @DisplayName("Days left includes February 29th in a leap year") + public void testDaysLeftInLeapYear() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 2, 1), LocalDate.of(2024, 3, 1))).isEqualTo(29); + } + + @Test + @Tag("task:3") + @DisplayName("No days left on the day the membership ends") + public void testDaysLeftOnEndDate() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 3, 20), LocalDate.of(2024, 3, 20))).isEqualTo(0); + } + + @Test + @Tag("task:3") + @DisplayName("No days left after the membership has ended") + public void testDaysLeftAfterEndDate() { + assertThat(frontDesk.daysLeft(LocalDate.of(2024, 4, 2), LocalDate.of(2024, 3, 20))).isEqualTo(0); + } + + @Test + @Tag("task:4") + @DisplayName("Duration of an evening visit") + public void testVisitDurationEvening() { + var expected = Duration.ofMinutes(95); + + assertThat(frontDesk.visitDuration( + LocalDateTime.of(2024, 3, 10, 18, 5), + LocalDateTime.of(2024, 3, 10, 19, 40))).isEqualTo(expected); + } + + @Test + @Tag("task:4") + @DisplayName("Duration of a visit that goes past midnight") + public void testVisitDurationPastMidnight() { + var expected = Duration.ofMinutes(105); + + assertThat(frontDesk.visitDuration( + LocalDateTime.of(2024, 3, 10, 23, 30), + LocalDateTime.of(2024, 3, 11, 1, 15))).isEqualTo(expected); + } + + @Test + @Tag("task:4") + @DisplayName("Duration of a visit includes seconds") + public void testVisitDurationWithSeconds() { + var expected = Duration.ofMinutes(45).plusSeconds(59); + + assertThat(frontDesk.visitDuration( + LocalDateTime.of(2024, 3, 10, 7, 0, 0), + LocalDateTime.of(2024, 3, 10, 7, 45, 59))).isEqualTo(expected); + } + + @Test + @Tag("task:5") + @DisplayName("Format a visit of more than an hour") + public void testFormatVisitHoursAndMinutes() { + assertThat(frontDesk.formatVisit(Duration.ofMinutes(95))).isEqualTo("1h 35m"); + } + + @Test + @Tag("task:5") + @DisplayName("Format a visit with fewer than ten minutes past the hour") + public void testFormatVisitPadsMinutes() { + assertThat(frontDesk.formatVisit(Duration.ofHours(2).plusMinutes(5))).isEqualTo("2h 05m"); + } + + @Test + @Tag("task:5") + @DisplayName("Format a visit of less than an hour, ignoring seconds") + public void testFormatVisitIgnoresSeconds() { + assertThat(frontDesk.formatVisit(Duration.ofMinutes(45).plusSeconds(59))).isEqualTo("0h 45m"); + } + + @Test + @Tag("task:5") + @DisplayName("Format a visit of more than a day") + public void testFormatVisitLongerThanADay() { + assertThat(frontDesk.formatVisit(Duration.ofHours(26).plusMinutes(10))).isEqualTo("26h 10m"); + } + + @Test + @Tag("task:5") + @DisplayName("Format an empty visit") + public void testFormatVisitZero() { + assertThat(frontDesk.formatVisit(Duration.ZERO)).isEqualTo("0h 00m"); + } +} diff --git a/exercises/settings.gradle b/exercises/settings.gradle index 019a3ee94..46b0c1fa4 100644 --- a/exercises/settings.gradle +++ b/exercises/settings.gradle @@ -12,6 +12,7 @@ include 'concept:cars-assemble' include 'concept:jedliks-toy-car' include 'concept:football-match-reports' include 'concept:gotta-snatch-em-all' +include 'concept:gym-front-desk' include 'concept:international-calling-connoisseur' include 'concept:karls-languages' include 'concept:lasagna'