Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subtracting a month does not work #32

Merged
merged 2 commits into from
Feb 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/kotlin/khronos/IntExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ val Int.years: Duration
get() = year

val Int.month: Duration
get() = Duration(unit = Calendar.MONTH, value = this - 1)
get() = Duration(unit = Calendar.MONTH, value = this)

val Int.months: Duration
get() = month
Expand Down
11 changes: 11 additions & 0 deletions src/test/kotlin/khronos/DurationTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,15 @@ class DurationTest {
assertEquals(expected = fiveYearsLater, actual = 5.years.since)
}

/**Test that subtracting a month results in the correct change to the date.*/
@Test fun subtractMonth() {
val n = Dates.today + 5.months
val dayNumber = n.dayByCalendar()
val monthNumber = n.monthByCalendar()
val monthAgo = n - 1.month
assert(monthAgo.dayByCalendar() == dayNumber)
val delta = (if (monthNumber == 0) 11 else monthNumber - 1)
assert(monthAgo.monthByCalendar() == delta)
}

}
4 changes: 2 additions & 2 deletions src/test/kotlin/khronos/IntExtensionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ class IntExtensionsTest {
}

@Test fun month() {
assertEquals(expected = Duration(unit = Calendar.MONTH, value = 0), actual = 1.month)
assertEquals(expected = Duration(unit = Calendar.MONTH, value = 1), actual = 1.month)
}

@Test fun months() {
assertEquals(expected = Duration(unit = Calendar.MONTH, value = 2), actual = 3.months)
assertEquals(expected = Duration(unit = Calendar.MONTH, value = 3), actual = 3.months)
}

@Test fun week() {
Expand Down
14 changes: 14 additions & 0 deletions src/test/kotlin/khronos/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,17 @@ fun assertVeryClose(maxOffset: Int = 200, from: Date, to: Date) {
fun assertEquals(expected: Duration, actual: Duration) {
Assert.assertEquals(expected, actual)
}

/**Returns the day of month for this date.*/
fun Date.dayByCalendar(): Int {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.get(Calendar.DAY_OF_MONTH)
}

/**Returns the month for this date.*/
fun Date.monthByCalendar(): Int {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar.get(Calendar.MONTH)
}